有些事情让我很困惑......我正在学习教程,但他没有介绍大部分代码是如何完成的。
使用 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/