Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing an array of custom objects in Realm

Tags:

swift

realm

I have an object called List which subclasses Realm's Object class:

class List: Object {
    dynamic var brandListItems: [BrandListItem] = []
}

and another object, BrandListItem which also subclasses to Object:

class BrandListItem: Object {
    dynamic var brandID: String?
    dynamic var name: String?
}

My app is crashing with the following error

'Property 'brandListItems' is declared as 'NSArray', which is not a supported RLMObject property type. All properties must be primitives, NSString, NSDate, NSData, NSNumber, RLMArray, RLMLinkingObjects, or subclasses of RLMObject.

I tried doing something like RLMArray<BrandListItem>() with no luck. How do I successfully save these objects to Realm?

like image 264
Zack Shapiro Avatar asked Mar 22 '17 18:03

Zack Shapiro


1 Answers

You need to use Realm's List<T> property. Note that it's not marked dynamic

https://realm.io/docs/swift/latest/#to-many-relationships

class List: Object {
   let brandListItems = RealmSwift.List<BrandListItem>()
}

Note that it's necessary to qualify Realm Swift's List<T> with its module to disambiguate it from your newly-declared List class.

like image 94
dmorrow Avatar answered Nov 17 '22 06:11

dmorrow