删除魔法记录导入时的孤立对象

时间:2014-06-16 18:25:03

标签: ios core-data magicalrecord

有没有内置魔法记录来处理孤儿?例如,如果我加载以下JSON数据......

[
  { "_id"   : "b1", "name"  : "brandA"},
  { "_id"   : "b2", "name"  : "brandB"},
  { "_id"   : "b3", "name"  : "brandC"}
]

然后数据会更新并移除brandC

[
  { "_id"   : "b1", "name"  : "brandA"},
  { "_id"   : "b2", "name"  : "brandB"}
]

更重要的是,如何删除孤立的嵌套对象,例如<{1}}

productB

1 个答案:

答案 0 :(得分:9)

想出来,但是如果有人愿意提出更好的解决方案,请这样做。

删除&#34;等级0和#34;在负载

NSArray *newdata   =  [];//AN ARRAY OF NEW DATA
NSArray *idList         = [newdata valueForKey:@"_id"];
NSPredicate *predicate  = [NSPredicate predicateWithFormat:@"NOT(_id IN %@)", idList];
[MRBrand MR_deleteAllMatchingPredicate:predicate];
[[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];

删除&#34; Level 1&#34;上的嵌套孤儿在托管对象中

-(void)willImport:(id)data{
    NSArray *idList         = [data[@"products"] valueForKey:@"_id"];
    NSPredicate *predicate  = [NSPredicate predicateWithFormat:@"NOT(pid IN %@) AND brand.bid == %@", idList, self.bid];
    [Product MR_deleteAllMatchingPredicate:predicate inContext:self.managedObjectContext];
}

willImport中的品牌实体上,我们正在搜索与新数据不匹配的产品ID并将其删除。