您的謂詞可以訪問通過名稱保存數組的對象的屬性;我在下面的例子中調用了list
。然後使用ANY
關鍵字檢查數組中的所有值,並使用BETWEEN
來確定這些值是否在您選擇的範圍內。
#import <Foundation/Foundation.h>
@interface Grumolo : NSObject
@property (copy, nonatomic) NSArray * list;
@end
@implementation Grumolo
- (NSString *)description
{
return [NSString stringWithFormat:@"%@: %p, list: %@", NSStringFromClass([self class]), self, [self list]];
}
@end
int main(int argc, const char * argv[])
{
@autoreleasepool {
float target = 234;
float delta = 0.8;
NSPredicate * p = [NSPredicate predicateWithFormat:@"ANY list BETWEEN %@", @[@(target-delta), @(target+delta)]];
NSArray * yes = @[@234, @10, @100];
NSArray * yes2 = @[@0, @16, @234];
NSArray * no = @[@1, @2, @3];
Grumolo * g1 = [Grumolo new];
[g1 setList:yes];
Grumolo * g2 = [Grumolo new];
[g2 setList:yes2];
Grumolo * g3 = [Grumolo new];
[g3 setList:no];
NSLog(@"%@", [@[g1, g2, g3] filteredArrayUsingPredicate:p]);
}
return 0;
}
你可能也想嘗試一下predicateWithBlock:
,這將讓你表達你想與在每個陣列傳統的循環做什麼,返回YES
如果你發現符合您的標準和NO
的元素,如果你用盡名單。
NSPredicate * pb = [NSPredicate predicateWithBlock:^BOOL(Grumolo * evaluatedObject, NSDictionary *bindings) {
NSArray * list = [evaluatedObject list];
__block BOOL result = NO;
[list enumerateObjectsUsingBlock:^(NSNumber * obj, NSUInteger idx, BOOL *stop) {
BOOL moreThanLower = (NSOrderedDescending == [obj compare:@(target-delta)]);
BOOL lessThanUpper = (NSOrderedAscending == [obj compare:@(target+delta)]);
if(moreThanLower && lessThanUpper){
*stop = YES;
result = YES;
return;
}
}];
return result;
}];
「任何列表之間」是讓它工作的關鍵。謝謝, – Koen