user3488542
user3488542

Reputation: 103

Declaring RLMArray property when using Realm Objective-C from Swift

class Post: RLMObject {
    var images: RLMArray!
    override init(JSON:json) {
        if let imagesArray = dictionary["images"].arrayObject {
            let imagesItems = RLMArray(objectClassName: StringObject.className())
            for dic in imagesArray {
                let image = StringObject(stringValue: dic as! String)
                imagesItems.addObject(image)
            }
            images = imagesItems
        }
    }
}

The code above I try to init PostModel include images property, but it alway crash in my project with:

'(null)' is not supported as an RLMArray object type. RLMArrays can only contain instances of RLMObject subclasses

I saw in the documentation for Realm Swift to use List<Foo> to declare the array property, but I don't know how to do so in my case.

Upvotes: 2

Views: 1500

Answers (1)

bdash
bdash

Reputation: 18308

When using Realm's Objective-C API from Swift, array properties should be declared with a default value that is an instance of RLMArray with the appropriate object class name. For instance:

class Post: RLMObject {
    dynamic var images = RLMArray(objectClassName: StringObject.className())

    // …
}

Note also the presence of the dynamic modifier. This is required to ensure that accesses of the property are dispatched dynamically to the getters and setters for the property that RLMObject creates.

Upvotes: 5

Related Questions