搜索结果始终为0(NSArray和NSPredicate)

时间:2010-10-29 16:44:19

标签: cocoa cocoa-touch nspredicate

我有一个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个对象,或者只要有与查询匹配的属性/方法,我就可以使用它来搜索任何对象(在此案例:姓名)?

提前致谢

1 个答案:

答案 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是空的吗?