使用MagicalRecord saveWithBlock添加关系中的对象不起作用

时间:2014-06-10 03:22:03

标签: ios core-data magicalrecord

执行保存块的代码:

[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) {

}];

股票模型:

@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

StockCategory模型:

@class Stock;

@interface StockCategory : NSManagedObject

@property (nonatomic, retain) NSString * categoryId;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSSet *stocks;
@end

@interface StockCategory (CoreDataGeneratedAccessors)

- (void)addStocksObject:(Stock *)value;
- (void)removeStocksObject:(Stock *)value;
- (void)addStocks:(NSSet *)values;
- (void)removeStocks:(NSSet *)values;

@end

json看起来像这样:

[
  {
    "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"
      }
    ],
  }
]

打开核心数据专业版,您只能看到名称为" iPad air"保存了它的类别。我无法弄清楚原因。你可以在saveWithBlock部分看到,我首先在上下文中找到与json中相同的_id,然后在关系中添加category对象。它起作用,但不是全部。这是为什么? enter image description here

1 个答案:

答案 0 :(得分:0)

看起来您需要更改数据模型以允许类别与Stock实体建立多对多关系。当你有一对一的关系时,你的代码将取代现有的关系。