views:

50

answers:

2

Sorry about the weird title... all will be explained.

Basically I have an array/dictionary structure like this in my app:

NSArray {

    NSDictionary {
        (NSString *)id;
        (NSDictionary *)dictionary;
    }

    NSDictionary {
        (NSString *)id;
        (NSDictionary *)dictionary;
    }

    NSDictionary {
        (NSString *)id;
        (NSDictionary *)dictionary;
    }

    etc...

}

Hope that's easy to work out...

Now I have an (NSString *)id and I want to get the (NSDictionary *)dictionary which corresponds to it.

Is there any way that I can do this?

Thank you

Tom

+2  A: 

Try something like this

for (NSDictionary *dict in dictArray) {
    if ([[dict objectForKey:@"id"] isEqualToString:targetID]){
        return [dict objectForKey:@"dictionary"];
    }
}

I have not compiled the code(don't have mac near me), but I think you got the idea. The basic idea is to loop through the array and compare query string. But if you have many items then this linear search might be time consuming.

taskinoor
is this the best way then? there's no "simpler" way at all?
Thomas Clayson
As you have an array of dictionary, no better way is coming to my mind right now. May be other members can suggest better ways.
taskinoor
+2  A: 

If the ids are unique, I'd use NSDictionary as my top level object instead of the NSArray. That way you can just do: [dict objectForKey:stringID]

NSArray doesn't really make sense here unless you are using it as a tables datasource.

Jason McCreary
Hmm, that is a good idea, but I have built all my code around this concept now. There was probably a very good reason why I didn't do it that way round to start off with. I can't quite remember what that is though.
Thomas Clayson
Comments are your friend ;) Yeah, I don't recommend changing your codebase. But something to keep in mind for the future. The only time I wrap within an `NSArray` is when I need it for a `UITableView`.
Jason McCreary