1

我一直在尝试使用 NSPredicate 过滤这个数组(充满了 NSDictionaries)......

我有非常少量的代码无法正常工作......

以下代码应将 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]);
4

3 回答 3

2

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

NSNumber *idNumber = [NSNumber numberWithLongLong:[[[mightyPlistDict objectForKey:@"pushesArr"] objectAtIndex:indexPath.row] longLongValue]];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"id = %@", idNumber];
于 2012-08-05T16:25:23.390 回答
0

你不确定“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"];
于 2012-08-05T16:31:43.837 回答
-1

NSPredicate 用于过滤数组,而不是对它们进行排序。要对数组进行排序,请使用sortedArrayUsingDescriptorsNSArray 的方法。

一个例子:

// 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]];
于 2012-08-05T16:22:06.030 回答