0

我有一个 NSDictionary 的 NSArray。所有的字典都有一个键image-path
我想获得一个过滤数组,其中仅包含path与 key 的给定值(我的变量的内容)匹配的字典image-path

我使用这一行验证了我拥有的数据的结构(它为我打印了关键图像路径的字典的所有值):

NSLog(@"array key paths: %@", [mountedImages valueForKeyPath:@"image-path"]);

我正在使用这段代码:

NSString *path = @"value-I-want-to-match";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(image-path LIKE[cd] \"%@\")", path];
NSArray *filteredArray = nil;
filteredArray = [mountedImages filteredArrayUsingPredicate:predicate];

最后一行崩溃并产生以下错误:

[ERROR] Computing 6571367.19831142 raised 'Unknown number type or nil passed to arithmetic function expression.'

我在 QuickLook 插件中执行此操作。我可以使用 gdb 单步执行我的代码,但我似乎没有得到任何跟踪。我只得到:

[...]
[ERROR] Computing 6571367.19831142 raised 'Unknown number type or nil passed to arithmetic function expression.'
[Switching to process 23335 thread 0x8903]
[Switching to process 23335 thread 0xa703]
[Switching to process 23335 thread 0x8903]
Program ended with exit code: 0
4

1 回答 1

2

您应该删除放置在谓词格式字符串中的转义引号。如 Apple 谓词格式字符串参考中所述:

当使用 %@ 将字符串变量替换为格式字符串时,它们被引号括起来。如果要指定动态属性名称,请在格式字符串中使用 %K,如下例所示。

 NSString *attributeName = @"firstName";
 NSString *attributeValue = @"Adam";
 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K like %@", attributeName, attributeValue];

在这种情况下,谓词格式字符串的计算结果为 firstName,如“Adam”。

单引号或双引号变量(或替换变量字符串)会导致 %@、%K 或 $variable 被解释为格式字符串中的文字,从而防止任何替换。在以下示例中,谓词格式字符串的计算结果为 firstName,如“%@”(注意 %@ 周围的单引号)。

 NSString *attributeName = @"firstName";
 NSString *attributeValue = @"Adam";
 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K like '%@'", attributeName, attributeValue];

在您的情况下,您的谓词被创建为image-path LIKE[cd] "%@",当用于过滤您的数组时无法正确评估。

于 2012-02-03T15:50:22.160 回答