Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RealmSwift initializers - Xcode fix-it keeps getting it wrong

Tags:

ios

swift

realm

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

like image 212
theDC Avatar asked Apr 24 '16 14:04

theDC


2 Answers

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)
    }
like image 195
kishikawa katsumi Avatar answered Nov 22 '22 07:11

kishikawa katsumi


Try:

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

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

like image 34
Austin Avatar answered Nov 22 '22 05:11

Austin