【问题标题】:Core Data: What difference between insertNewObject vs designated initializer核心数据:insertNewObject 与指定初始值设定项有什么区别
【发布时间】:2016-12-08 15:49:27
【问题描述】:

我找到了两个解决问题的方法:

public class MyClass: NSManagedObject {
    init(_ entity:NSEntityDescription, dict: NSDictionary, context: NSManagedObjectContext) {
        super.init(entity: entity , insertInto: context)
    }
}

let entity = NSEntityDescription.entity(forEntityName: "MyClass", in: self.context!)
_ = MyClass.init(entity!, dict: item as! NSDictionary, context: self.context!)

let myClass = NSEntityDescription.insertNewObject(forEntityName: "MyClass", into: context) as! MyClass

但我无法理解最终的区别。又对NSManagedObjectContext有何影响?

【问题讨论】:

  • 我不知道第一个版本,但我为您准备了第三个版本:let createe = MyClass(context: context),我更愿意避免知道实体名称的需要。
  • official doc here 确实提到了 insertNewObject 和 init 的关系

标签: ios objective-c swift core-data nsmanagedobjectcontext


【解决方案1】:

具有相同的效果。 NSEntityDescription 上的方法是一种“工厂”方法,在 Objective-C 中你不会经常看到(该方法在 Swift 之前就已经存在)。但最终结果与使用指定的初始化程序相同。虽然工厂方法的代码不可用,但您可以假设它在某个时候调用了指定的初始化程序。

【讨论】:

    【解决方案2】:

    init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) 初始化器可用于 iOS 3.0+

    init(context: NSManagedObjectContext) 初始化器可用于 iOS 10.0+

    我使用这两个初始化器来保持与 iOS

    【讨论】:

      猜你喜欢
      • 2021-02-13
      • 2018-04-30
      • 1970-01-01
      • 2020-07-20
      • 1970-01-01
      • 2016-06-24
      • 1970-01-01
      • 2022-11-20
      • 2023-03-23
      相关资源
      最近更新 更多