ZW2652
ZW2652

Reputation: 79

How to save an array to a Realm Object

I am new to using Realm. Is there an easy way to save an array to a realm object? I am receiving my data from a JSON REST call:

class SomeClass: RLMObject {

    dynamic var id = 0
    dynamic var name = ""
    dynamic var array: NSArray


    func checkForUpdates() {
        // Download JSON data here... The results have an array inside of them.

        SomeClass.createOrUpdateInDefaultRealmWithObject(SomeNSDictionary)         


    }

    override class func primaryKey() -> String! {
        return "id"
    }
}

Is it possible to save the array in the JSON results in Realm?

Thanks.

Upvotes: 3

Views: 8495

Answers (1)

jpsim
jpsim

Reputation: 14409

Realm has a special RLMArray type, which allows storing a collection of RLMObject's tied to a parent RLMObject. For example, say you had the following JSON:

{
  "name": "John Doe",
  "aliases": [
    {"alias": "John"},
    {"alias": "JD"}
  ]
}

You could model this with the following classes:

class Alias: RLMObject {
  dynamic var alias = ""
}

class Person: RLMObject {
  dynamic var name = ""
  dynamic var aliases = RLMArray(objectClassName: "Alias")
}

So you could simply create a Person object with the following API call:

Person.createInRealm(realm, withObject: jsonObject)

You can learn more about how RLMArrays work from Realm's reference documentation: http://realm.io/docs/cocoa/0.80.0/api/Classes/RLMArray.html

Upvotes: 8

Related Questions