RealmSwift initializers - Xcode fix-it keeps getting it wrong

蓝咒 提交于 2019-12-08 16:37:41

问题


I cannot get Realm working when I want to provide initializer for a class, Xcode endlessly suggest errors.

I decided to upload two screenshots instead of code snippet to make it easier to see errors

I follow the suggestions and end up with this

The last error tells "Use of undeclared type 'RLMObjectSchema'

I use the latest 0.99 version of RealmSwift


回答1:


The recommended way is creating memberwise convenience initializer, like the following:

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
    }

    ...
}

You cannot omit default initializer because Realm needs default initializer for instantiating objects for querying. When querying to the Realm, Realm calls default initializer internally to instantiate the objects.

You can also override default initializer, but we don't recommend it. Because when you override the default initializer, you should override other required initializers inherited from ObjC layer due to Swift type system limitation. Also you should import both Realm and RealmSwift frameworks. Because there are Objective-C only class in the parameters of those initializers.

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



回答2:


Try:

required convenience init(...) {
    self.init()
    ...
}

See https://github.com/realm/realm-cocoa/issues/1849



来源:https://stackoverflow.com/questions/36824202/realmswift-initializers-xcode-fix-it-keeps-getting-it-wrong

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!