创建一个“beginswith”NSPredicate

Hor*_*ray -1 objective-c nsarray nspredicate

我正在尝试创建一个 NSPredicate 来搜索数组,然后检查该数组中是否有任何对象以其他字符串开头。这是我的代码。它让我崩溃了,所以显然出了什么问题。

array = [[NSArray alloc] initWithObjects:@"Hello", @"What", @"Maybe", nil];

NSString *string = @"H";

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@ BEGINSWITH %@", string, array];

NSArray *filteredArray = [array filteredArrayUsingPredicate:predicate];
NSLog(@"%@", filteredArray);
Run Code Online (Sandbox Code Playgroud)

这是崩溃错误:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can't do a substring operation with something that isn't a string (lhs = H rhs = (
    Hello,
    What,
    Maybe
))'
Run Code Online (Sandbox Code Playgroud)

然后它在错误中给出了一堆数字,如果您愿意,我可以发布,请告诉我。

mat*_*att 6

该错误准确地告诉您问题是什么。看看错误。然后看看你的代码:

[NSPredicate predicateWithFormat:@"%@ BEGINSWITH %@", string, array]
Run Code Online (Sandbox Code Playgroud)

字符串怎么可能以数组开头?你的谓词是废话。

所以这就是困难的根源之一——你懒得去阅读错误消息。困难的另一个来源是您懒得阅读文档。您还没有停下来了解 NSPredicate 格式实际上是什么。文档在这里:

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Predicates/Articles/pSyntax.html

我认为就你的情况而言,你想说的当然是更明智的事情,如下所示:

[NSPredicate predicateWithFormat:@"SELF BEGINSWITH %@", string]
Run Code Online (Sandbox Code Playgroud)

尝试一下,看看是否能得到您期望的结果。