2010-10-29 69 views
0

我已經像這樣限定,其保持Foo對象的NSArray搜索結果總是0(NSArray的和NSPredicate)

@interface Foo : NSObject <NSCopying> { 
    NSString *name; 
} 
@property (nonatomic, retain) NSString *name; 
@end 

和查詢:

NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:@"name BEGINSWITH[cd] %@", filterString]; 
//NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:@"name CONTAINS[cd] %@", filterString]; 
filteredArray = [[originalArray filteredArrayUsingPredicate:filterPredicate] mutableCopy]; 

,這是行不通的。我總是得到0結果。

所以,我的問題是:

應該我總是用NSPredicate與特定鍵搜索只NSDictionary對象或我可以使用它,只要有一個屬性/方法與查詢匹配搜索任何對象(在這種情況下:姓名)?

在此先感謝

回答

2

您的代碼是正確的。我試了一下:

@interface Foo : NSObject 

@property (nonatomic, retain) NSString * name; 

@end 
@implementation Foo 

@synthesize name; 

@end 

NSMutableArray * a = [NSMutableArray array]; 
for (int i = 0; i < 100; ++i) { 
    Foo * f = [[Foo alloc] init]; 
    [f setName:[NSString stringWithFormat:@"%d", i]]; 
    [a addObject:f]; 
    [f release]; 
} 

NSPredicate * p = [NSPredicate predicateWithFormat:@"name BEGINSWITH[cd] %@", @"1"]; 
NSArray * filtered = [a filteredArrayUsingPredicate:p]; 
NSLog(@"%@", [filtered valueForKey:@"name"]); 

日誌:

2010-10-29 10:51:22.103 EmptyFoundation[49934:a0f] (
    1, 
    10, 
    11, 
    12, 
    13, 
    14, 
    15, 
    16, 
    17, 
    18, 
    19 
) 

這使我問:你originalArray空?

+0

.....或'nil'? – 2010-10-29 19:11:24

+0

或'nil' .... :) – 2010-10-29 19:25:03

+0

謝謝,事實上它似乎是正確的,我意識到我的錯誤是在別的地方。 ( – nacho4d 2010-10-30 06:00:33