作为CoreData的初学者,我到目前为止已经找到了三种不同的方法来实例化NSManagedObject的实例:
1:
let myEntity = NSEntityDescription.entityForName("MyEntity", inManagedObjectContext: managedContext)!
let instance = MyEntity(entity: myEntity, insertIntoManagedObjectContext: managedContext)
instance.someProperty = someValue
try! managedContext.save()
2:
let myEntity = NSEntityDescription.entityForName("MyEntity",
inManagedObjectContext:managedContext)
let instance = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)
instance.setValue(someValue, forKey: "someProperty")
try! managedContext.save()
3:
let instance = NSEntityDescription.insertNewObjectForEntityForName("MyEntity", inManagedObjectContext: managedContext) as! MyEntity
instance.somePropery = someValue
try! managedContext.save()
这些方法之间是否存在显着差异?
答案 0 :(得分:0)
前两种方法完全相同。在这两种情况下,您使用相同的NSManagedObject
init方法。
NSEntityDescription.insertNewObjectForEntityForName(_ entityName: String, inManagedObjectContext context: NSManagedObjectContext)
的文档说明此方法“在概念上类似于”NSManagedObject.init(entity entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?)
因此,您可以使用任何方便的方法。