Add objects in relationship not work using MagicalRecord saveWithBlock
Posted
by
yong ho
on Stack Overflow
See other posts from Stack Overflow
or by yong ho
Published on 2014-06-10T03:22:02Z
Indexed on
2014/06/10
3:24 UTC
Read the original article
Hit count: 453
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?
© Stack Overflow or respective owner