ios - 在 convenience init Swift 3 中获取类名

标签 ios swift core-data nsmanagedobject initializer

我正在尝试实现我自己的 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' used before self.init call

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

最佳答案

可以得到self的类型与 type(of: 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检查以使用新的 init(context:) iOS 10/macOS 10.12 或更高版本上的初始化程序,以及兼容性代码 作为旧操作系统版本的后备:

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)
        }
    }
}

关于ios - 在 convenience init Swift 3 中获取类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40824573/

相关文章:

ios - 具有多个循环的 Json 解析

swift - 对成员 'buildBlock()' 的模糊引用

algorithm - 从任意坐标向外遍历二维数组到边界

ios - 如何根据多个 Core Data 属性的计算值进行排序

ios - 核心数据中的位置通过 NSFetchedResultsController 按距离排序?

iphone - 如何使用 NSFetchedResultsController 支持像 iPhone 照片应用程序一样管理 UITableView 上的数据

ios - 在 iOS 设备上滚动时,元素的 z-index 不起作用

ios - 如何使用自定义单元格中的按钮获取自定义 UITableViewCell 的行,该按钮将发送到 deleteRowsAtIndexPaths

iphone - 将文本设置为自定义表格单元格标签时崩溃

ios - 在 Swift/iOS 中获取动画期间的动画高度