我开始使用Realm.io,我需要添加或更新To-Many关系RLMObject。想象一下,我有这样的RLMObjects:
#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有一个主键(id),我正在阅读一个人和各种狗的json。 我怎样才能添加这个人和他们的狗?
我将循环json人和狗阵列。例如,如果我使用上面的代码,关于Dogs对象的主键违规的领域警告:
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];
答案 0 :(得分:1)
如果您收到此错误'Primary key can't be changed after an object is inserted.'
,原因是因为您尝试使用同一个对象。
dog.id = 1;
dog.name = @"Lupi";
[realm addOrUpdateObject:dog];
dog.id = 2; // This is not allowed. The primary key of the object that was saved once can not be changed.
dog.name = @"rex";
[realm addOrUpdateObject:dog];
Realm对象不是一个正确的值对象。当Realm对象保存一次时,它将被更改为连接到数据库的特殊对象。
所以dog.id = 2;
意味着您将更改刚刚保存的对象。
每次要保存新对象时,都应创建新实例。 如下所示:
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];
如果您将从JSON创建新对象,如下所示:
{
"person": {
"id": 1,
"name": "foo",
"birthdate": "1980/10/28",
"dogs": [
{
"id": 1,
"name": "bar"
},
{
"id": 2,
"name": "baz"
}
]
}
}
你可以循环dog数组,在每个循环中创建新的Realm对象。
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"];
for (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];