ios - 将对象保存到核心数据中

标签 ios xcode swift core-data

有些事情让我很困惑......我正在学习教程,但他没有介绍大部分代码是如何完成的。

使用 NSManagedObject 子类的教程,他第一次检查样本数据是否在 Core Data 中我们使用 return 跳过如果用户第一次启动应用程序,示例数据将进入核心数据。 让我们来看看。

 func inserSampleData()
  {
    let fetchRequest = NSFetchRequest(entityName: "Bowtie")
    fetchRequest.predicate = NSPredicate(format: "searchKey != nil")

    let count = managedContext.countForFetchRequest(fetchRequest, error: nil)

    if count > 0 { return } //break if we have the sample data already in the core data

    let path = NSBundle.mainBundle().pathForResource("SampleData", ofType: "plist")

    let dataArray = NSArray(contentsOfFile: path!)

    for dict in dataArray!
    { //1
        let entity = NSEntityDescription.entityForName("Bowtie", inManagedObjectContext: self.managedContext)
        let bowtie = Bowtie(entity: entity!, insertIntoManagedObjectContext: self.managedContext)
        let btDict = dict as! NSDictionary

       //// SOME CODE

        var error: NSError?

        if !managedContext.save(&error)
        {
            println("Some error \(error?.userInfo)")
        }

    }
  }

在评论 1 中,他使用 NSEntityDescription 来获取实体的对象, 我相信我们这样做是为了将样本数据保存到核心数据中,除非我们调用 NSEntityDescription...

让我们看一下第二个func wear()

  func wear() {
    //currentBowtie is an instance of the NSManagedObject Subclass
    let times = currentBowtie.timesWorn.integerValue
    currentBowtie.timesWorn = NSNumber(integer: times + 1)
    currentBowtie.lastWorn = NSDate()

    var error: NSError?

    if managedContext.save(&error)
    {
        println("unable to save \(error) \(error?.userInfo)")
    }

  }

根据第二个函数,他直接保存到磁盘,没有指定实体,也没有调用 NSEntityDescription.entityForName...

那么应用程序如何知道要保存在哪个实体中?

为什么他在 Func insertSampleData() 中调用了 NSEntityDescription,而在 func wear() 中却没有使用它?

最佳答案

在 Core Data 中创建新的 Bowtie 时,您需要一个实体描述。

currentBowtie 已创建,因此可以进一步使用它并保存它不需要实体描述。

关于ios - 将对象保存到核心数据中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32381033/

相关文章:

c++ - iOS集成unity 4.6.3项目(64位&& IL2CPP)。出现如下这样的错误,如何解决呢?

ios - 表格 View 滚动更改选择

swift - 通过拖放文件或文件夹来启动 Swift OSX 应用程序

iOS10 UIColor 变化

ios - 在中间增加 ScrollView 高度

ios - Swift Sprite Kit 相机运动

Swift 3 单元测试 - 使用 import @testable 时链接器失败

ios - 如何将 UITextField 中的数字转换为 float ?

java - 如何在 Swift 中将 Int 位模式转换为 Float?

ios - 在钥匙串(keychain)中找不到有效的 iOS 代码签名 key