我有一个NSArray
,其中包含Foo
个定义的对象:
@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
个对象,或者只要有与查询匹配的属性/方法,我就可以使用它来搜索任何对象(在此案例:姓名)?
提前致谢
答案 0 :(得分: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
是空的吗?