NSManagedObject(context:) 构造函数和 NSEntityDescription.insertNewObject 将新对象插入 CoreData 的区别

Difference among NSManagedObject(context:) constructor and NSEntityDescription.insertNewObject for inserting new object into CoreData

2 个代码示例,能够将新对象插入 CoreData。

我想知道,NSManagedObject(context:)NSEntityDescription.insertNewObject在插入新对象时有什么区别吗?

我们什么时候应该选择一个而不是另一个?

NSManagedObject(上下文:)

let coreDataStack = CoreDataStack.INSTANCE
let backgroundContext = coreDataStack.backgroundContext

backgroundContext.perform {
    let nsTabInfo = NSTabInfo(context: backgroundContext)
    
    nsTabInfo.name = "..."
    
    if backgroundContext.hasChanges {
        do {
            try backgroundContext.save()
        } catch {
            let nserror = error as NSError
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }
}

NSEntityDescription.insertNewObject

let coreDataStack = CoreDataStack.INSTANCE
let backgroundContext = coreDataStack.backgroundContext

backgroundContext.perform {
    let nsTabInfo = NSEntityDescription.insertNewObject(forEntityName: "NSTabInfo", into: backgroundContext) as! NSTabInfo
    
    nsTabInfo.name = "..."
    
    if backgroundContext.hasChanges {
        do {
            try backgroundContext.save()
        } catch {
            let nserror = error as NSError
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }
}

以下是文档对它们每个的说明。


convenience init(context moc: NSManagedObjectContext)

Initializes a managed object subclass and inserts it into the specified managed object context.

This method is only legal to call on subclasses of NSManagedObject that represent a single entity in the model.


class func insertNewObject(forEntityName entityName: String, 
                      into context: NSManagedObjectContext) -> NSManagedObject

Creates, configures, and returns an instance of the class for the entity with a given name.

This method makes it easy for you to create instances of a given entity without worrying about the details of managed object creation. The method is conceptually similar to the following code example.


第一个是在 iOS 10 中引入的,它使 NSManagedObject 的实例化看起来更自然。

两者有以下区别-

  1. 第二种方法强制您对 entityName 使用 String - 因此它容易出错,而第一种方法始终适用于您的 NSManagedObject subclass,而无需使用 String你的名字。
  2. 第一个比第二个更具可读性。
  3. 第一个存在局限性 - This method is only legal to call on subclasses of NSManagedObject that represent a single entity in the model.如果您在数据模型中使用实体子class,如 Animal > Dog,这可能会产生问题]。文档中的这一行指的是多个实体使用相同 class 名称的数据模型。这是不寻常但合法的。实体继承对此没有影响。