我有一个对象数组,每个都有一个id,我想得到item.objectID在一个id数组中包含的所有项目,我怎样才能得到那个结果?
我试图做但我在创建predicateWithFormat时遇到错误:无法解析格式字符串:
NSString *predicateFormat = [NSString stringWithFormat:@"SELF.itemID CONTAIN IN (1,2,3,4,5,6,7,8)"];
NSPredicate *predicate = [NSPredicate predicateWithFormat: predicateFormat];
filteredData = [localData filteredArrayUsingPredicate:predicate];
我只是想避免这种情况:
NSString *predicateFormat = [NSString stringWithFormat:@"SELF.itemID = 1 OR SELF.itemID = 2 OR SELF.itemID = 3"];
NSPredicate *predicate = [NSPredicate predicateWithFormat: predicateFormat];
filteredData = [localData filteredArrayUsingPredicate:predicate];
因为要为过滤器添加其他条件。
答案 0 :(得分:7)
你几乎拥有它:)
NSArray *objects = @[
@{
@"itemID" : @1
},
@{
@"itemID" : @2
},
@{
@"itemID" : @3
},
@{
@"itemID" : @4
},
@{
@"itemID" : @5
}
];
NSArray *idsToLookFor = @[@3, @4];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"itemID IN %@", idsToLookFor];
NSArray *result = [objects filteredArrayUsingPredicate:predicate];
NSLog(@"result: %@", result);
如果您不想传入任何数组,但是“手持”编写谓词,则语法为:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"itemID IN { 3, 4 }"];
结果将是:
result: (
{
itemID = 3;
},
{
itemID = 4;
}
)
答案 1 :(得分:5)
只需要IN
:
NSArray * desiredIDs = @[@1, @2, @3, @4, @5];
NSString * predicateFormat = [NSString stringWithFormat:@"SELF.itemID IN %@", desiredIDs];
...