How to store an array in a Realm object

I am new to using Realm. Is there an easy way to store the array in a realm object? I am getting 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 store an array in JSON results in Realm?

Thank.

+3


source to share


1 answer


Realm has a special type RLMArray

that allows you to keep a collection RLMObject

tied to its parent RLMObject

. For example, let's say you had the following JSON:

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

      

You can simulate 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 can just create an object Person

with the following API call:

Person.createInRealm(realm, withObject: jsonObject)

      

You can read more about how it RLMArray

works in the Realm reference documentation: http://realm.io/docs/cocoa/0.80.0/api/Classes/RLMArray.html

+8


source







All Articles