如果我是NSLOG()我正在尝试搜索的数组,我会得到这个...
(
{
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;
}
)
这很好但我需要做的是能够有一个方法让我输入一个id然后它返回匹配的screen_name作为NSString。我怎么能这样做是调用数组。
我认为NSPredicate是我正在寻找的但我不确定......
NSArray *twitterInfo;
答案 0 :(得分:3)
是的,NSPredicate就是你想要的。像这样:
NSString yourID; // assume this contains the id you want
NSPredicate *pred = [NSPredicate predicateWithFormat:@"id = %@", yourID];
NSString *screenName = [[[twitterInfo filteredArrayUsingPredicate:pred] lastObject] objectForKey:@"screen_name"];
答案 1 :(得分:0)
我偏爱使用块的枚举(比谓词更容易理解: - ):
NSInteger desiredID = ...;
__block NSString *userName;
NSString *name = [twitterInfo enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL *stop)
{
NSInteger theID = [[dict objectForKey:@"id"] integerValue];
NSLog(@"Check ID %d against %d", theID, desiredID); // just to see its working
if(theID == desiredID) {
userName = [dict objectForKey:@"screen_name"];
*stop = YES;
}
} ];
如果userName在此末尾为nil,则找不到id。