2010-10-29 43 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