简体   繁体   中英

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.

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 RLMArray s work from Realm's reference documentation: http://realm.io/docs/cocoa/0.80.0/api/Classes/RLMArray.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM