RealmSwift初始值设定项:在super.init调用之前自行使用 [英] RealmSwift initializer: self used before super.init call
问题描述
import RealmSwift
import Realm
public class Card : Object {
var username : String
var firstName : String
var lastName : String
init?(dictionary: [String:Any]?) {
guard let dictionary = dictionary , let username = dictionary["username"] as? String else { return else}
self.username = username
self.firstName = firstName
self.lastName = lastName
}
required public init() {
fatalError("init() has not been implemented")
}
required public init( realm: RLMRealm, schema: RLMObjectSchema) {
fatalError("init(realm:schema:) has not been implemented")
}
required public init( value: Any, schema: RLMSchema) {
fatalError("init(value:schema:) has not been implemented")
}
}
我得到:
在super.init调用之前使用'self'
'self' used before super.init call
我的课堂正常工作.添加RealmSwift之后,我遇到了这些错误.如果我添加super.init()
它会抱怨:
I had my class working properly. After adding RealmSwift i'm getting those errors. If I add super.init()
it complains:
未在super.init调用中初始化属性'self.username'
Property 'self.username' not initialized at super.init call
推荐答案
这里发生了几件事.
首先,当添加自定义初始化程序时对于Object
的子类,必须将它们声明为便捷初始化程序.不可能从子类中正确实现Object
所需的初始化程序,而使用便捷的初始化程序将消除尝试执行此操作的需要.这也意味着您将改为从自定义初始化程序中将其委托给self.init()
而不是super.init()
.
First and foremost, when adding custom initializers to subclasses of Object
, they must be declared as convenience initializers. It's not possible to correctly implement Object
's required initializer from a subclass, and using a convenience initializer removes the need to try and do this. It also means you'll instead delegate to self.init()
rather than super.init()
from within your custom initializer.
第二,存储的属性必须具有初始值.如果没有初始值,Swift编译器将不会为您的类合成初始化程序(在这种情况下,是调用基类的init()
版本).
Secondly, stored properties must have an initial value. Without the initial value the Swift compiler will not synthesize initializers for your class (in this case, a version of init()
that calls through to the base class).
最后,正如我在其他地方提到的那样,必须使用Swift的dynamic
修饰符声明类型String
的属性,以允许Realm截获对它们的获取/设置操作.
Finally, as I mentioned elsewhere, properties of type String
must be declared using Swift's dynamic
modifier to allow Realm to intercept get / set operations on them.
通过遵循这些准则,您将得到如下结果:
By following these guidelines you'll end up with something like so:
public class Card : Object {
dynamic var username: String = ""
dynamic var firstName: String = ""
dynamic var lastName: String = ""
convenience init?(dictionary: [String:Any]?) {
guard let dictionary = dictionary,
let username = dictionary["username"] as? String,
let firstName = dictionary["firstName"] as? String,
let lastName = dictionary["lastName"] as? String
else { return nil }
self.init()
self.username = username
self.firstName = firstName
self.lastName = lastName
}
}
这篇关于RealmSwift初始值设定项:在super.init调用之前自行使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!