How to save an array to a Realm Object

我与影子孤独终老i 提交于 2020-01-03 20:11:31

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/27135188/how-to-save-an-array-to-a-realm-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!