尝试使用NSPredicate过滤NSMutableArray并获取错误

时间:2013-09-05 14:05:14

标签: ios

我正在尝试过滤我保留在我的应用中的员工联系人列表的结果,但是收到以下错误:'无法在集合中使用/ contains运算符LAST(不是集合)'

我已经尝试了NSPredicate命令的几个变体,self,self.last,employee.last,last =='smith'(这个不生成错误但不返回任何结果)。

NSMutableArray *employeesList = [[NSMutableArray alloc] init];
Person2 *employee = [[Person2 alloc] init];

employee.first = @"bob";
employee.last = @"black";
[employeesList addObject:employee];

employee = [[Person2 alloc] init];
employee.first = @"jack";
employee.last = @"brown";
[employeesList addObject:employee];

employee = [[Person2 alloc] init];
employee.first = @"george";
employee.last = @"smith";
[employeesList addObject:employee];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"last contains[cd] %@", @"black"];
NSArray *filteredKeys = [employeesList filteredArrayUsingPredicate:predicate];
NSLog(@"filtered : %@",filteredKeys);

[person2.h]

@interface Person2 : NSObject

{
  @private  
}

@property (nonatomic, retain) NSString *first;
@property (nonatomic, retain) NSString *last;

+ (Person2 *)personWithFirst:(NSString *)first andLast:(NSString *)last;

@end

[person2.m]

#import "Person2.h"

@implementation Person2
@synthesize first, last;

- (id)init {
    self = [super init];
    if (self) {
    }

return self;
}

+ (Person2 *)personWithFirst:(NSString *)first andLast:(NSString *)last {
Person2 *person = [[Person2 alloc] init];
[person setFirst:first];
[person setLast:last];
return person;
} 

- (NSString *)description {
return [NSString stringWithFormat:@"%@ %@", [self first], [self last]];
}

@end

2 个答案:

答案 0 :(得分:0)

我有一个NSArray类别,很容易做到这一点:

@interface NSArray (FilterAdditions)
- (NSArray *)filterObjectsUsingBlock:(BOOL (^)(id obj, NSUInteger idx))block;
@end


@implementation NSArray (FilterAdditions)

- (NSArray *)filterObjectsUsingBlock:(BOOL (^)(id, NSUInteger))block {
    NSMutableArray *result = [NSMutableArray array];
    [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if (block(obj, idx)) {
            [result addObject:obj];
        }
    }];
    return result;
}

所以你会这样称呼它:

NSArray *filteredEmployees = 
[employeeList filterObjectsUsingBlock:^BOOL(id obj, NSUInteger idx){ 
    return [(Person2 *)obj.last isEqualToString:@"black"];
}];

答案 1 :(得分:0)

所以我找到了答案,现在我觉得非常愚蠢! “first”和“last”的使用是保留名称,不能使用。我将变量更改为firstName和lastName,它完美地运行。

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Predicates/Articles/pSyntax.html

感谢大家的意见和帮助。