gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 17:44:19 25 4
gpt4 key购买 nike

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

提前致谢

最佳答案

您的代码是正确的。我试过了:

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

关于cocoa - 搜索结果始终为 0(NSArray 和 NSPredicate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4054029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com