2014-06-10 19 views
0

的代碼以執行保存塊不工作:添加在關係的對象使用MagicalRecord saveWithBlock

[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,然後在關係中添加類別對象。它正在工作,但不是全部。這是爲什麼? enter image description here

回答

0

看起來您需要更改您的數據模型以允許類別與庫存實體之間具有多對多關係。當你有一對一的關係時,你的代碼將取代現有的關係。

+0

我有庫存的關係<<->>類別。但是他們都沒有反過來。 –

相關問題