Re: looking for reference to a dictionary
Re: looking for reference to a dictionary
- Subject: Re: looking for reference to a dictionary
- From: "Michael Ash" <email@hidden>
- Date: Wed, 22 Oct 2008 10:50:44 -0400
On Tue, Oct 21, 2008 at 12:08 PM, Stefan Wolfrum
<email@hidden> wrote:
> Hi all,
>
> I have an array. Each array entry is a dictionary. Each dictionary has two
> key/value pairs (all are strings).
>
> Now I get from somewhere else the value (a string) corresponding to one of
> the keys. It's exactly the same string, content-wise (not address-wise).
> What I need: a reference/pointer to THAT dictionary inside the array which
> contains this string as the value of the key (I know what key it is).
>
> How would I do that?
>
> My knowledge is: to get an array's entry I just have the objectAtIndex:
> method. But then I'd need the index where the dictionary I'm looking for is.
> How would I get the index without, of course, iterating through all the
> array's entries and looking at every dictionary and comparing my given value
> with all the values inside the dictionaries?
When you say "the value of the key", do you mean that the string is
literally the key in the dictionary, or that the string is equal to
[dictionary objectForKey:@"someKnownKey"]?
If the latter, then this code will do it:
NSUInteger index = [[array valueForKey:@"someKnownKey"] indexOfObject:string];
id obj = index != NSNotFound ? [array objectAtIndex:index] : nil;
Note that this does not avoid iterating the entire array, it just
avoids making you write code that does. The speed hit is still there.
Indeed, the speed hit *must* be there if you use an array, as others
have discussed. But it makes the code nicer.
If you're literally searching for a dictionary which contains a
specific key (not a specific value for a specific key) then I don't
think there is any way to do this short of writing your own for loop
and searching manually.
Mike
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden