【问题标题】:Saving objects into core data将对象保存到核心数据中
【发布时间】:2015-09-03 16:31:49
【问题描述】:

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

教程使用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() 中使用它?

【问题讨论】:

    标签: ios xcode swift core-data


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-15
      • 2010-11-09
      • 1970-01-01
      相关资源
      最近更新 更多