2013-09-05 43 views
1

我想過濾員工聯繫人列表的結果,我留在我的應用程序,但我得到以下錯誤:'不能用於/包含操作符與集合最後(不是一個集合)'試圖過濾NSMutableArray與NSPredicate並獲取錯誤

我已經嘗試了NSPredicate命令,self,self.last,employee.last,last =='smith'(這個不會產生錯誤,但不會產生錯誤, t返回任何結果)。

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 
+0

howz your employeesList看起來像?你的數組是數組的對象,爲什麼你在數組中添加多個對象?它非常糟糕 – iPatel

+0

@iPatel什麼? –

+1

你想達到什麼目的?根據姓氏匹配過濾數組,還是試圖檢索數組中姓氏匹配的最後一個人? –

回答

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"]; 
}];