在easy init Swift 3中获取类名

Mar*_*ges 5 core-data initializer nsmanagedobject ios swift

我正在尝试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)
}
Run Code Online (Sandbox Code Playgroud)

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

在self.init电话之前使用'self'

有谁知道如何解决这个错误,或以另一种方式实现相同的结果.

Mar*_*n R 7

你可以获得selfwith 的类型,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)
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)