我正在尝试实现我自己的 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/