objective c - Adding objects To-Many Relationships RLMObject -
i'm starting use realm.io , need add or update to-many relationship rlmobject. imagine have rlmobjects this:
#import <realm/realm.h> @class person; // dog model @interface dog : rlmobject @property nsinteger id; @property nsstring *name; @end rlm_array_type(dog) // define rlmarray<dog> // person model @interface person : rlmobject @property nsstring *name; @property nsdate *birthdate; @property rlmarray<dog *><dog> *dogs; @end rlm_array_type(person) // define rlmarray<person>
dogs rlmobject has primary key (id) , i'm reading json 1 person , various dogs. how can add person , dogs?
i'll loop json person , dogs array. if use above code example, realm warning primary key violation on dogs object:
rlmrealm *realm = [rlmrealm defaultrealm]; dogs *dog = [[dogs alloc] init]; [realm beginwritetransaction]; dog.id = 1; dog.name = @"lupi"; [realm addorupdateobject:dog]; dog.id = 2; dog.name = @"rex"; [realm addorupdateobject:dog]; [realm commitwritetransaction]; person *newperson = [[person alloc] init]; [realm beginwritetransaction]; newperson.id = 1; newperson.name = @"john"; [newperson.dogs addobject:dog]; [realm addorupdateobject:newperson]; [realm commitwritetransaction];
if error 'primary key can't changed after object inserted.'
, reason because you're trying use same object.
dog.id = 1; dog.name = @"lupi"; [realm addorupdateobject:dog]; dog.id = 2; // not allowed. primary key of object saved once can not changed. dog.name = @"rex"; [realm addorupdateobject:dog];
realm object not value object. when realm object saved once, changed special object connected database.
so dog.id = 2;
means change object saved.
you should create new instance every time when you'd save new objects. following:
dog *dog1 = [[dog alloc] init]; dog1.id = 1; dog1.name = @"lupi"; [realm addorupdateobject:dog1]; dog *dog2 = [[dog alloc] init]; dog2.id = 2; dog2.name = @"rex"; [realm addorupdateobject:dog2]; [realm commitwritetransaction];
create objects json
if create new objects json following:
{ "person": { "id": 1, "name": "foo", "birthdate": "1980/10/28", "dogs": [ { "id": 1, "name": "bar" }, { "id": 2, "name": "baz" } ] } }
you can loop dogs array, create new realm objects every loop.
nsdictionary *json = [nsjsonserialization jsonobjectwithdata:data options:0 error:nil]; nsdictionary *person = json[@"person"]; [realm beginwritetransaction]; person *newperson = [[person alloc] init]; newperson.id = [person[@"id"] integervalue]; newperson.name = person[@"name"]; nsarray *dogs = person[@"dogs"]; (nsdictionary *dog in dogs) { dog *newdog = [[dog alloc] init]; newdog.id = [dog[@"id"] integervalue]; newdog.name = dog[@"name"]; [realm addorupdateobject:newdog]; } [realm addorupdateobject:newperson]; [realm commitwritetransaction];
Comments
Post a Comment