theDC
theDC

Reputation: 6484

RealmSwift initializers - Xcode fix-it keeps getting it wrong

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

enter image description here

I follow the suggestions and end up with this

enter image description here

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

I use the latest 0.99 version of RealmSwift

Upvotes: 8

Views: 1802

Answers (2)

kishikawa katsumi
kishikawa katsumi

Reputation: 10573

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

Upvotes: 13

Austin
Austin

Reputation: 1437

Try:

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

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

Upvotes: 1

Related Questions