ios - NSManagedObject(context :) constructor and NSEntityDescription. insertNewObject 用于将新对象插入到 CoreData 中的区别

标签 ios swift core-data

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. 第二种方法强制您使用String作为entityName - 因此很容易出错,而第一种方法始终适用于您的NSManagedObject子类,而无需使用字符串y 名称。
  2. 第一个比第二个更具可读性。
  3. 第一个方法有一个限制 - 此方法只能合法地调用代表模型中单个实体的 NSManagedObject 子类。如果您这样做,这可能会产生问题在数据模型中使用实体子类化,例如 Animal > Dog。文档中的这一行指的是多个实体使用相同类名的数据模型。这是不寻常但合法的。实体继承不会影响这一点。

关于ios - NSManagedObject(context :) constructor and NSEntityDescription. insertNewObject 用于将新对象插入到 CoreData 中的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67980475/

相关文章:

iphone - 在 Objective-C 中对数组进行排序

ios - 使用 UICollectionViewDiffableDataSource 和 NSFetchedResultsController 重新排序单元格

Swift 3 从单链表中删除节点

ios - UITableView自定义删除按钮功能

字体更改时自动调整 uiLabel 和 uiTableViewCell 大小的 iphone 代码?

ios - NSTimer 在后台运行 - 需要每小时触发一次

ios - 搜索栏 Controller iOS 11 问题 - 搜索栏和范围按钮重叠

ios - 无法创建新的模型版本

ios - 核心数据 - 关系、获取和插入

ios - 自动同步 iOS 应用程序 (Objective-C) 本地数据库与 MySQL 数据库