使用NSPredicate删除对象

我有这个有许多子字典的词典。 如何使用NSPredicate从父字典中删除isChanged = 1对象?

 { "0_496447097042228" = { cellHeight = 437; isChanged = 1; }; "100000019882803_193629104095337" = { cellHeight = 145; isChanged = 0; }; "100002140902243_561833243831980" = { cellHeight = 114; isChanged = 1; }; "100004324964792_129813607172804" = { cellHeight = 112; isChanged = 0; }; "100004324964792_129818217172343" = { cellHeight = 127; isChanged = 0; }; "100004324964792_129835247170640" = { cellHeight = 127; isChanged = 1; }; } 

作为使用NSPredicate的简单替代方法,您可以使用NSDictionary内置的keysOfEntriesPassingTest:此答案假设“isChanged”是一个NSString,值0或1是一个NSNumber:

 NSSet *theSet = [dict keysOfEntriesPassingTest:^(id key, id obj, BOOL *stop) { return [obj[@"isChanged"] isEqualToNumber: @1]; }]; 

返回的集合是通过testing的密钥列表。 从那里,你可以删除所有匹配的:

[dict removeObjectsForKeys:[theSet allObjects]];

我用以下方式解决了我的问题:

 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"isChanged == %d", 1]; NSArray *allObjs = [parentDict.allValues filteredArrayUsingPredicate:predicate]; [allObjs enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { NSMutableArray *keys = [[NSMutableArray alloc] initWithCapacity:0]; [keys setArray:[parentDict allKeysForObject:obj]]; [parentDict removeObjectsForKeys:keys]; [keys release]; }]; 

如果有字典数组,则可以使用NSPredicate删除所选类别的数据

这里是代码

 NSString *selectedCategory = @"1"; //filter array by category using predicate NSPredicate *predicate = [NSPredicate predicateWithFormat:@"isChanged == %@", selectedCategory]; NSArray *filteredArray = [yourAry filteredArrayUsingPredicate:predicate]; [yourAry removeObject:[filteredArray objectAtIndex:0]]; 

但是在你的问题中,数据不在数组中,而是在字典中

你的数据应该是这种格式

 ( { cellHeight = 437; isChanged = 1; }, { cellHeight = 145; isChanged = 0; }, { cellHeight = 114; isChanged = 1; } )