Add objects in relationship not work using MagicalRecord saveWithBlock
- by yong ho
The code to perform a save block:
[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {
for (NSDictionary *stockDict in objects) {
NSString *name = stockDict[@"name"];
Stock *stock = [Stock MR_createInContext:localContext];
stock.name = name;
NSArray *categories = stockDict[@"categories"];
if ([categories count] > 0) {
for (NSDictionary *categoryObject in categories) {
NSString *categoryId = categoryObject[@"_id"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"categoryId == %@", categoryId];
NSArray *matches = [StockCategory MR_findAllWithPredicate:predicate inContext:localContext];
NSLog(@"%@", matches);
if ([matches count] > 0) {
StockCategory *cat = [matches objectAtIndex:0];
[stock addCategoriesObject:cat];
}
}
}
}
} completion:^(BOOL success, NSError *error) {
}];
The Stock Model:
@class StockCategory;
@interface Stock : NSManagedObject
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSSet *categories;
@end
@interface Stock (CoreDataGeneratedAccessors)
- (void)addCategoriesObject:(StockCategory *)value;
- (void)removeCategoriesObject:(StockCategory *)value;
- (void)addCategories:(NSSet *)values;
- (void)removeCategories:(NSSet *)values;
@end
The json look like this:
[
{
"name": "iPad mini ",
"categories": [
{
"name": "iPad",
"_id": "538c655fae9b3e1502fc5c9e",
"__v": 0,
"createdDate": "2014-06-02T11:51:59.433Z"
}
],
},
{
"name": "iPad Air ",
"categories": [
{
"name": "iPad",
"_id": "538c655fae9b3e1502fc5c9e",
"__v": 0,
"createdDate": "2014-06-02T11:51:59.433Z"
}
],
}
]
Open the core data pro, You can see only stock with the name of "iPad air" has it's categories saved. I just can't figure out why. You can see in the saveWithBlock part, I first find in the context for the same _id as in json, and then add the category object in the relationship. It's working, but not all of them. Why is that?