The Man
The Man

Reputation: 1462

Searching An NSArray of NSDictionaries

If I NSLOG() the array that I'm trying to search I get this...

(
    {
    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;
}
)

This is fine but what I need to do is to be able to have a method that lets me put in an id and then it returns the matching screen_name as an NSString. How could I do this is the array is called.

I think NSPredicate is what I'm looking for but I'm not sure...

NSArray *twitterInfo;

Upvotes: 0

Views: 316

Answers (2)

David Hoerl
David Hoerl

Reputation: 41662

I'm partial to using enumeration with blocks (easier to understand than predicates :-):

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;
  }
} ];

If userName is nil at the end of this, the id was not found.

Upvotes: 0

Chuck
Chuck

Reputation: 237110

Yep, NSPredicate is what you want. Something like this:

NSString yourID; // assume this contains the id you want
NSPredicate *pred = [NSPredicate predicateWithFormat:@"id = %@", yourID];
NSString *screenName = [[[twitterInfo filteredArrayUsingPredicate:pred] lastObject] objectForKey:@"screen_name"];

Upvotes: 3

Related Questions