【问题标题】:Get class name in convenience init Swift 3在方便的 init Swift 3 中获取类名
【发布时间】:2016-11-27 00:25:43
【问题描述】:

我正在尝试实现我自己的 convenience init(context moc: NSManagedObjectContext) 版本,这是 iOS 10 中 NSManagedObject 上的新便利初始化程序。原因是我需要使其与 iOS 9 兼容。

我想出了这个:

convenience init(managedObjectContext moc: NSManagedObjectContext) {
    let name = "\(self)".components(separatedBy: ".").first ?? ""

    guard let entityDescription = NSEntityDescription.entity(forEntityName: name, in: moc) else {
        fatalError("Unable to create entity description with \(name)")
    }

    self.init(entity: entityDescription, insertInto: moc)
}

但是由于这个错误它不起作用......

'self' 在 self.init 调用之前使用

有谁知道如何解决这个错误,或者以另一种方式获得相同的结果。

【问题讨论】:

    标签: ios swift core-data nsmanagedobject initializer


    【解决方案1】:

    您可以使用type(of: self) 获取self 的类型,并且 甚至在 self 初始化之前就可以工作。 String(describing: <type>) 将非限定类型名称作为 字符串(即没有模块名称的类型名称),即 正是你需要的:

    extension NSManagedObject {
        convenience init(managedObjectContext moc: NSManagedObjectContext) {
            let name = String(describing: type(of: self))
    
            guard let entityDescription = NSEntityDescription.entity(forEntityName: name, in: moc) else {
                fatalError("Unable to create entity description with \(name)")
            }
    
            self.init(entity: entityDescription, insertInto: moc)
        }
    }
    

    您还可以添加 if #available 检查以在 iOS 10/macOS 10.12 或更高版本上使用新的 init(context:) 初始化程序,以及兼容性代码 作为旧操作系统版本的后备方案:

    extension NSManagedObject {
        convenience init(managedObjectContext moc: NSManagedObjectContext) {
            if #available(iOS 10.0, macOS 10.12, *) {
                self.init(context: moc)
            } else {
                let name = String(describing: type(of: self))
                guard let entityDescription = NSEntityDescription.entity(forEntityName: name, in: moc) else {
                    fatalError("Unable to create entity description with \(name)")
                }
                self.init(entity: entityDescription, insertInto: moc)
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 2013-09-03
      • 1970-01-01
      相关资源
      最近更新 更多