0

我正在尝试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]]];

我在这里做错了什么?

4

2 回答 2

2

Apple 的谓词编程指南指出“Cocoa 中的谓词表达式由 NSExpression 的实例表示”。请注意,它NSExpression提供了一种可以通过FUNCTION关键字调用方法调用的语法。文档将语法定义为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;
    }
)

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

于 2013-04-04T04:05:26.737 回答
-1
NSString *functionStr = @"T-r";
NSArray *arr = [myarr filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(function == %@)",functionStr]];


Here myarr is NSMutableArray.
Try with this code.
于 2013-04-04T06:13:01.137 回答