使用NSPredcate筛选NSArray/NSDictionary



我一直在尝试使用NSPredcate筛选这个数组(其中充满了NSDictionary)。。。

我有一小部分代码不起作用。。。

以下代码应该将label.text更改为AmyBurnett34,但它没有。。。

NSPredicate *pred = [NSPredicate predicateWithFormat:@"id = %@", [[mightyPlistDict objectForKey:@"pushesArr"] objectAtIndex:indexPath.row]];
    NSLog(@"%@",pred);
    label.text = [[[twitterInfo filteredArrayUsingPredicate:pred] lastObject] objectForKey:@"screen_name"];
    NSLog(@"%@",twitterInfo);

以下是NSLoged。。。

2012-08-05 11:39:45.929 VideoPush[1711:707] id == "101323790"
2012-08-05 11:39:45.931 VideoPush[1711:707] (
        {
        id = 101323790;
        "screen_name" = AmyBurnett34;
    },
        {
        id = 25073877;
        "screen_name" = realDonaldTrump;
    },
        {
        id = 159462573;
        "screen_name" = ecomagination;
    },
        {
        id = 285234969;
        "screen_name" = "UCB_Properties";
    },
        {
        id = 14315150;
        "screen_name" = MichaelHyatt;
    }
)

只是为了提醒一下,如果你也NSLog这个。。。数组为空。。。

NSLog(%@,[twitterInfo filteredArrayUsingPredicate:pred]);

问题是谓词使用的是与字符串进行比较,而内容使用的是数字。试试这个:

NSNumber *idNumber = [NSNumber numberWithLongLong:[[[mightyPlistDict objectForKey:@"pushesArr"] objectAtIndex:indexPath.row] longLongValue]];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"id = %@", idNumber];

您不能确定"id"的值是否是字符串,它可能是NSNumber。我建议:

NSUInteger matchIdx = ...;
NSUInteger idx = [array indexOfObjectPassingTest:^BOOL(NSDictionary *dict, NSUInteger idx, BOOL *stop)
{
  id obj = [dict objectForKey:@"id"];
  // NSLog the class if curious using NSStringFromClass[obj class];
  NSUInteger testIdx = [obj integerValue]; // works on strings and numbers
  return testIdx == matchIdx;
}
if(idx == NSNotFound) // handle error
NSString *screenName = [[array objectAtIndex:idx] objectForKey:@"screen_name"];

NSPredcate用于筛选数组,而不是进行排序。要对数组进行排序,请使用NSArray的sortedArrayUsingDescriptors方法。

一个例子:

// Define a sort descriptor based on last name.
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"lastName" ascending:YES];    
// Sort our array with the descriptor.
NSArray *sortedArray = [originalArray sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor, nil]];

最新更新