'使用NSPredicate的predicateWithFormat时,无法解析格式字符串“function ==%@”':

时间:2013-04-04 02:28:55

标签: ios objective-c nspredicate

我正在尝试通过“NSArray”属性搜索function。我在控制台上打印数组时的输出如下:

<__NSArrayI 0xa523b40>(
{
    category = "010-T";
    description = "<h3>Opleidingen</h3>";
    function = "T-r";
    name = "Michal Jordan";
    photo = "http://dws.com/34.jpg";
},
{
    category = "010-T";
    description = "abcd";
    function = "AB";
    name = "Pvt MSK";
    photo = "http://test.com/3.jpg";
},
{
    category = "010-T";
    description = "def";
    function = "T-r";
    name = "Sanu M";
    photo = "http://abc.com/1.jpg";
}
)

此代码按'category'搜索,有效:

NSString *categoryStr = @"010-T";
NSArray *arr = [NSArray arrayWithArray:[myarr filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"category == %@",categoryStr]]];

但是当我尝试使用以下代码(按function搜索)时,抛出了异常:

NSString *functionStr = @"T-r";
NSArray *arr = [NSArray arrayWithArray:[myarr filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"function == %@",functionStr]]];

例外是:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "function == %@"'

所以看来function是一个保留关键字。

我尝试了以下代码,用单引号包装function,但结果是arr有0个对象。

NSArray *arr = [NSArray arrayWithArray:[myarr filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"'function' == %@",functionStr]]];

我在这里做错了什么?

2 个答案:

答案 0 :(得分:2)

Apple的Predicate Programming Guide指出,Cocoa中的谓词表达式由NSExpression的实例表示。&#34;请注意,NSExpression提供了一种语法,可以通过FUNCTION关键字调用方法调用。 The docs将语法定义为FUNCTION(receiver, selectorName, arguments, ...)。虽然我在任何文档中都没有找到对此的引用,但似乎此功能不包括在其他上下文中使用文字单词函数。

幸运的是,您可以使用%K格式说明符以替代方式构建谓词格式字符串,该说明符用于键名。例如,[NSPredicate predicateWithFormat:@"%K == %@", @"function", @1]不会抛出异常并且可以正常工作。请参阅以下代码中的实际操作:

    NSDictionary *dict1 = @{@"otherKey": @1, @"function" : @2};
    NSDictionary *dict2 = @{@"otherKey": @2, @"function" : @1};
    NSArray *array = @[dict1, dict2];
    NSPredicate *otherKeyPredicate = [NSPredicate predicateWithFormat:@"%K == %@",@"otherKey", @1];
    NSArray *filteredByOtherKey = [array filteredArrayUsingPredicate:otherKeyPredicate];
    NSPredicate *functionPredicate = [NSPredicate predicateWithFormat:@"%K == %@", @"function", @1];
    NSArray *filteredByFunction = [array filteredArrayUsingPredicate:functionPredicate];
    NSLog(@"filteredByOtherKey = %@", filteredByOtherKey);
    NSLog(@"filteredByFunction = %@", filteredByFunction);

我们在控制台上获得以下输出:

filteredByOtherKey = (
        {
        function = 2;
        otherKey = 1;
    }
)
filteredByFunction = (
        {
        function = 1;
        otherKey = 2;
    }
)

以这种方式构建谓词可能稍微有些工作,但将来会阻止这些类型的冲突。前进的一个好习惯是将格式字符串限制为仅包含格式说明符和谓词语法,在运行时最终确定prediate的表达式字符串。

答案 1 :(得分:-1)

NSString *functionStr = @"T-r";
NSArray *arr = [myarr filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(function == %@)",functionStr]];


Here myarr is NSMutableArray.
Try with this code.