Reputation: 105
I get data List from Server. They are array of books. I have RLMObjects of books, book, person.
@class Person, Book;
@interface Person : RLMObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) int age;
@property (nonatomic, assign) NSInteger id;
@end
RLM_ARRAY_TYPE(Person)
@interface Book : RLMObject
@property (nonatomic, strong) Person *author;
@property (nonatomic, strong) NSString *price;
@property (nonatomic, strong) RLMArray<Person> *translators;
@end
RLM_ARRAY_TYPE(Book)
@interface Books : RLMObject
@property (nonatomic, assign) NSInteger count;
@property (nonatomic, strong) NSString *year;
@property (nonatomic, strong) RLMArray<Book> *books;
@end
@implementation Person
+ (NSString *)primaryKey {
return @"id";
}
@end
When I get array of books, turn them from dictionary to the Books object. Then add it into realm.
[[RLMRealm defaultRealm] transactionWithBlock:^{
[[RLMRealm defaultRealm] addObject:[Books mj_objectWithKeyValues:responseObject]];
} error:nil];
It crashed.Because there're two books which had same translators. Can't set primary key property 'id' to existing value '1314331'.
So, like this situation, how to put data into RLMRealm and keep every person object is the only one by primaryKey?
Upvotes: 0
Views: 280
Reputation: 357
Try this
[[RLMRealm defaultRealm] transactionWithBlock:^{
RLMObject *object = [Books mj_objectWithKeyValues:responseObject];
[[RLMRealm defaultRealm] addOrUpdateObject:object];
} error:nil];
Upvotes: 1