Search code examples
objective-crealm

How to store list of primitives (NSString) on Realm database


I'm trying to take advantage of a feature introduced in Realm Cocoa 3.0: Store a list of primitives. Previous to that version the only way to do it was creating a new subclass of RLMObject containing a property like @property NSString *stringValue and then creating an RLMArray property on the model intended to use an array of strings, integers or any other primitive. See this answer for more information.

According to the Realm Cocoa 3.0 announcement we have now support for Arrays of primitives, which in an example using Swift shows that it is possible to create a database model as

class Student : Object {
    @objc dynamic var name: String = ""
    let testScores = List<Int>()
}

So, how do I create a property like this one using Objective-C? I've been trying to do something like the following code:

@interface Game : RLMObject
@property NSString *name;
@property RLMArray<NSString *> *tags;  // First attempt
// @property NSArray<NSString> *tags;  // Second attempt
@end

My attempts are, until now, unsuccessful as I am getting an error: Terminating app due to uncaught exception 'RLMException', reason: 'Property 'tags' requires a protocol defining the contained type - example: RLMArray<Person>.'


Solution

  • From Realm's documentation:

    RLMArrays can store primitive values in lieu of Realm objects. In order to do so, constrain a RLMArray with one of the following protocols: RLMBool, RLMInt, RLMFloat, RLMDouble, RLMString, RLMData, or RLMDate.

    Your declaration would be:

    @property RLMArray<RLMString> *tags;
    

    Or, if you want to also make use of Objective-C generics:

    @property RLMArray<NSString *><RLMString> *tags;