在Swift 3中使用方便的初始化方法获取类名

5

我正在尝试实现自己的版本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.init调用之前使用了'self'

有人知道如何避免此错误,或以其他方式实现相同的结果吗?

1个回答

7
你可以使用type(of: self)获取self的类型,这在初始化self之前也是有效的。String(describing: )将无资格限定的类型名称作为字符串返回(即不带模块名称的类型名称),这正是你需要的:
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)
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接