Get class name in init swift 3 convenience

I am trying to implement my own version convenience init(context moc: NSManagedObjectContext), the new convenience initializer in NSManagedObject in iOS 10. The reason is that I need to make it compatible with iOS 9.

I came up with this:

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

but this does not work due to this error ...

'self' used before calling self.init

Does anyone know how to get around this error or achieve the same result in a different way.

+4
source share
1 answer

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

Source: https://habr.com/ru/post/1662045/


All Articles