7

解释起来有点困难,但我正在尝试使用 NSPredicate 通过 ids 过滤具有自定义 NSManagedObject 的数组。我有一个可以发送更新、删除或添加新对象的服务器,我需要控制 JSON 文件中的这些对象是否已经存在,如果存在则更新它们,如果不存在则插入核心数据。

我现在正在使用这个谓词:

   NSPredicate *predicate = [NSPredicate predicateWithFormat:@"storeId != %@", [jsonFile valueForKey:@"Id"];

其中 jsonFile 包含未解析的 Store 对象。但是有了这个谓词,它会给我一个巨大的数组,因为一个 id 将不同于某些 storeId,而下一个 id 将匹配。

Json 文件是这样的:

     "Stores":[{
          "id":1,
          "name":"Spar",
          "city":"London"
          }
          {
           "id":2,
           "name":"WalMart",
           "city":"Chicago"
       }];
4

2 回答 2

12

我不确定我是否正确理解您要达到的目标,但也许您可以使用以下内容:

NSArray *jsonFile = /* your array of dictionaries */;
NSArray *idList = [jsonFile valueForKey:@"id"]; // array of "id" numbers
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT(storeId IN %@)", idList];

这将给出所有具有storeId不等于 jsonFile数组中任何 id 的托管对象。

于 2012-07-30T13:41:33.537 回答
0

谓词的语法可能是关闭的 - 其他人可能会建议修复 - 但如果你有一个数组,为什么不使用

- (NSUInteger)indexOfObjectPassingTest:(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate

因为它更容易:

NSInteger textID = ... // you set this
NSInteger idx = [myArray indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop)) 
{
NSInteger objIdx = [obj objectForKey:@"id"] integerValue]; // integerValue works for both NSNUmbers and NSStrings
if(objIdx == testID) {
    return YES;
    *stop = YES;
}
}
于 2012-07-30T13:08:32.747 回答