0

如果我 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;
4

2 回答 2

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"];
于 2012-07-31T22:50:13.090 回答
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。

于 2012-07-31T23:20:41.827 回答