[英]Filtering NSArray/NSDictionary using NSPredicate
I've been trying to filter this array (which is full of NSDictionaries) using NSPredicate... 我一直在尝试使用NSPredicate过滤该数组(充满了NSDictionaries)...
I have a very small amount of code that just isn't working... 我有很少的代码无法正常工作...
The following code should change label.text to AmyBurnett34, but it doesn't... 以下代码应将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);
And here is what gets NSLoged... 这就是获取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;
}
)
Just for the heads up if you also NSLog this... the array is empty... 请注意,如果您也NSLog this ...数组为空...
NSLog(%@,[twitterInfo filteredArrayUsingPredicate:pred]);
The problem is that your predicate is using comparing with a string and your content is using a number. 问题在于您的谓词正在使用与字符串进行比较,而您的内容正在使用数字。 Try this: 尝试这个:
NSNumber *idNumber = [NSNumber numberWithLongLong:[[[mightyPlistDict objectForKey:@"pushesArr"] objectAtIndex:indexPath.row] longLongValue]];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"id = %@", idNumber];
You don't know for sure that the value of "id" is a string - it might be a NSNumber. 您不确定“ id”的值是否是字符串-它可能是NSNumber。 I suggest: 我建议:
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"];
NSPredicate is used for filtering arrays, not sorting them. NSPredicate用于过滤数组,而不是对其进行排序 。 To sort an array, use the sortedArrayUsingDescriptors
method of NSArray. 要对数组排序,请使用NSArray的sortedArrayUsingDescriptors
方法。
An an example: 一个例子:
// 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]];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.