RealmSwift初始化程序 – Xcode修复程序 – 它一直搞错了
当我想为一个类提供初始化工具时,我无法获得Realm的工作,Xcode无止境地提示错误。
我决定上传两个截图而不是代码片段,以便更容易看到错误
我遵循这些build议,并以此结束
最后一个错误告诉“使用未声明的types'RLMObjectSchema'
我使用RealmSwift的最新0.99版本
推荐的方法是创build成员方便初始值设定项,如下所示:
class Item: Object { dynamic var isBook: Bool = true dynamic var numberOfPages: Double = 0 dynamic var isInForeignLanguage: Bool = true dynamic var isFictional: Bool = true dynamic var value: Int { get { return calculalatedValue() } } convenience init(isBook: Bool, numberOfPages: Double, isInForeignLanguage: Bool, isFictional: Bool) { self.init() self.isBook = isBook self.numberOfPages = numberOfPages self.isInForeignLanguage = isInForeignLanguage self.isFictional = isFictional } ... }
你不能省略默认的初始值设定项,因为Realm需要默认的初始值设定项来实例化查询对象。 向Realm查询时,Realm会在内部调用默认的初始化程序来实例化对象。
你也可以重写默认的初始化程序,但是我们不推荐它。 因为当你重写默认的初始值设定项时,你应该覆盖由于Swifttypes的系统限制而从ObjC层inheritance的其他需要的初始值设定项。 你也应该导入Realm
和RealmSwift
框架。 因为这些初始化器的参数中只有Objective-C类。
import RealmSwift import Realm // Need to add import if you override default initializer! class Item: Object { dynamic var isBook: Bool = true dynamic var numberOfPages: Double = 0 dynamic var isInForeignLanguage: Bool = true dynamic var isFictional: Bool = true dynamic var value: Int { get { return calculalatedValue() } } required init() { super.init() } required init(realm: RLMRealm, schema: RLMObjectSchema) { super.init(realm: realm, schema: schema) } required init(value: AnyObject, schema: RLMSchema) { super.init(value: value, schema: schema) }
尝试:
required convenience init(...) { self.init() ... }