1

我正在尝试过滤我保留在我的应用程序中的员工联系人列表的结果,但出现以下错误:'Can't use in/contains operator with collection LAST (not a collection)'

我用 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

[人2.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
4

2 回答 2

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"];
}];
于 2013-09-05T15:21:19.633 回答
0

所以我找到了答案,现在我觉得很愚蠢!“first”和“last”的使用是保留名称,不能使用。我将变量更改为 firstName 和 lastName 并且效果很好。

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

谢谢大家的意见和帮助。

于 2013-09-05T16:32:10.557 回答