don*_*ile 51 iphone objective-c nsarray nsset nspredicate
如何在NSSet或NSArray中搜索具有特定属性特定值的对象?
示例:我有一个包含20个对象的NSSet,并且每个对象都有一个type属性.我想获得第一个拥有的对象[theObject.type isEqualToString:@"standard"].
我记得有可能以某种方式使用谓词来表示这种东西,对吗?
Ole*_*ann 78
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"type == %@", @"standard"];
NSArray *filteredArray = [myArray filteredArrayUsingPredicate:predicate];
id firstFoundObject = nil;
firstFoundObject = filteredArray.count > 0 ? filteredArray.firstObject : nil;
Run Code Online (Sandbox Code Playgroud)
注意:NSSet中第一个找到的对象的概念没有意义,因为集合中对象的顺序是未定义的.
NSR*_*der 17
您可以像Jason和Ole所描述的那样获得过滤后的数组,但由于您只需要一个对象,我会使用- indexOfObjectPassingTest:(如果它在一个数组中)或-objectPassingTest:(如果它在一个集合中)并避免创建第二个数组.
Car*_*zey 15
通常,我使用,indexOfObjectPassingTest:因为我觉得用Objective-C代码而不是NSPredicate语法来表达我的测试更方便.这是一个简单的例子(想象integerValue实际上是一个属性):
NSArray *array = @[@0,@1,@2,@3];
NSUInteger indexOfTwo = [array indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
return ([(NSNumber *)obj integerValue] == 2);
}];
NSUInteger indexOfFour = [array indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
return ([(NSNumber *)obj integerValue] == 4);
}];
BOOL hasTwo = (indexOfTwo != NSNotFound);
BOOL hasFour = (indexOfFour != NSNotFound);
NSLog(@"hasTwo: %@ (index was %d)", hasTwo ? @"YES" : @"NO", indexOfTwo);
NSLog(@"hasFour: %@ (index was %d)", hasFour ? @"YES" : @"NO", indexOfFour);
Run Code Online (Sandbox Code Playgroud)
此代码的输出是:
hasTwo: YES (index was 2)
hasFour: NO (index was 2147483647)
Run Code Online (Sandbox Code Playgroud)
NSArray* results = [theFullArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF.type LIKE[cd] %@", @"standard"]];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34353 次 |
| 最近记录: |