views:

171

answers:

2

I can't seem to work out how to get a Dictionary representing an object from the dictionary that TouchJSON returns.

For example:

If I use the JSON in the format here:

http://search.twitter.com/search.json?q=hello

How would I get a tweet with the "id" = x without having to pull all of the tweets into an array using a "for" statement?

e.g. without having to do this... since I know the "id" (JSON key, rather than index) of the object I want to access

NSArray *tweetsArray = [resultsDictionary objectForKey:@"results"];
 for (NSDictionary *tweetDictionary in tweetsArray) {
     NSString *tweetText = [tweetDictionary objectForKey:@"text"];
     [tweets addObject:tweetText];

 }
+1  A: 

You can use NSPredicate to filter the tweetsArray like this:

NSArray *tweetsArray = [resultsDictionary objectForKey:@"results"];
NSArray* filtered = [test filteredArrayUsingPredicate:
                          [NSPredicate predicateWithFormat:@"id = %@",@"456"]];

NSDictionary* tweet = [filtered lastObject];
tonklon
Did this answer your question?, then please mark as answered. Or have I misunderstood it?
tonklon
I don't know what exactly the filteredArrayUsingPredicate: do, but I think it still has to loop over the array some ways and it looks like a performance problem to the questioner. Take a look at the question again: " How would I get a tweet with the "id" = x without having to pull all of the tweets into an array using a "for" statement? "
vodkhang
A: 

Why don't you filter the id=x condition when you are parsing the JSON. This will make sure you traverse the JSON data only once.

This can only be a better solution if you have to access the JSON just for the id=x condition.

Girish Kolari