实例化NSManagedObject实例的不同方法

时间:2016-04-05 08:49:23

标签: core-data

作为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()

这些方法之间是否存在显着差异?

1 个答案:

答案 0 :(得分:0)

前两种方法完全相同。在这两种情况下,您使用相同的NSManagedObject init方法。

NSEntityDescription.insertNewObjectForEntityForName(_ entityName: String, inManagedObjectContext context: NSManagedObjectContext)的文档说明此方法“在概念上类似于”NSManagedObject.init(entity entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?)

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSEntityDescription_Class/#//apple_ref/occ/clm/NSEntityDescription/insertNewObjectForEntityForName:inManagedObjectContext

因此,您可以使用任何方便的方法。