如何使用 NSPredicate CONTAINS IN 数组获取所有项目
How to get all items with NSPredicate CONTAINS IN array
我有一个对象数组,每个对象都有一个 ID,我想获取 ID 数组中 item.objectID 包含的所有项目,我怎样才能得到那个结果?
我尝试做什么,但在创建 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];
因为还有其他条件要添加过滤。
你几乎成功了:)
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);
如果你不想传入任何数组,而是写谓词"in hand",语法是:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"itemID IN { 3, 4 }"];
结果将是:
result: (
{
itemID = 3;
},
{
itemID = 4;
}
)
只需要 IN
个:
NSArray * desiredIDs = @[@1, @2, @3, @4, @5];
NSString * predicateFormat = [NSString stringWithFormat:@"SELF.itemID IN %@", desiredIDs];
...
我有一个对象数组,每个对象都有一个 ID,我想获取 ID 数组中 item.objectID 包含的所有项目,我怎样才能得到那个结果?
我尝试做什么,但在创建 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];
因为还有其他条件要添加过滤。
你几乎成功了:)
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);
如果你不想传入任何数组,而是写谓词"in hand",语法是:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"itemID IN { 3, 4 }"];
结果将是:
result: (
{
itemID = 3;
},
{
itemID = 4;
}
)
只需要 IN
个:
NSArray * desiredIDs = @[@1, @2, @3, @4, @5];
NSString * predicateFormat = [NSString stringWithFormat:@"SELF.itemID IN %@", desiredIDs];
...