在便捷初始化Swift 3中获取类名 [英] Get class name in convenience init Swift 3
问题描述
我正在尝试实现自己的版本 convenience init(context moc:NSManagedObjectContext)
,这是iOS 10中NSManagedObject上的新便利初始化程序。原因是我需要使其与iOS 9兼容。
I'm trying to implement my own version of convenience init(context moc: NSManagedObjectContext)
, the new convenience initialiser on NSManagedObject in iOS 10. Reason being I need to make it compatible with 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)
}
但由于此错误而无法使用...
but it doesn't work because of this error...
'self'在self.init之前使用呼叫
'self' used before self.init call
有人知道如何解决此错误,或者以其他方式实现相同的结果。
Does anyone know how to get around this error, or achieve the same result in another way.
推荐答案
您可以使用<$ c $来获取 self
的类型。 c> type(of:self),并且
甚至在 self
初始化之前就可以工作。
String(描述:< type>)
以
字符串的形式返回无条件的类型名(即没有模块名的类型名),并且正是您在这里需要的
:
You can get the type of self
with type(of: self)
and that
works even before self
is initialized.
String(describing: <type>)
returns the unqualified type name as a
string (i.e. the type name without the module name), and that is
exactly what you need here:
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)
}
}
如果#available >检查以在iOS 10 / macOS 10.12或更高版本上使用新的 init(context:)
初始化程序,并将兼容性代码
作为旧OS版本的后备:
You can also add an if #available
check to use the new init(context:)
initializer on iOS 10/macOS 10.12 or later, and the compatibility code
as a fallback on older OS versions:
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)
}
}
}
这篇关于在便捷初始化Swift 3中获取类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!