Re: efficient searching of arrays
Re: efficient searching of arrays
- Subject: Re: efficient searching of arrays
- From: email@hidden
- Date: Mon, 14 Aug 2006 18:04:42 -0400
Consider using a different data structure. If you're looking to
search the list of objects based on a key (and you're doing it
frequently) then a key-value structure makes a lot more sense. Using
an NSDictionary, all you have to do is [dictionary objectForKey:
[anObject objectID]].
If you want your objects in an array, you can also get fast access to
items if you keep them sorted by your objectID. You could do a
binary search on that which has O(lg(n)) time. I doubt it's worth
doing all that work when you could use the dictionary approach and be
finished pretty quickly. Even if you want to have the dictionary and
the array, the memory overhead shouldn't be too big.
- Whitney Young
On Aug 14, 2006, at 3:21 PM, Mike Abdullah wrote:
Let's say I have an NSArray of several hundred instances of
MyObject. MyObject has a simple accessor method:
- (long)objectID;
I want to find the instance of MyObject whose objectID is 204.
What would be the best way of doing this? At present, the only
thing I can really think of is:
NSEnumerator *objectsEnumerator = [myArray objectEnumerator];
MyObject *anObject;
while (anObject = [objectsEnumerator nextObject])
{
if ([anObject objectID] == 204)
return anObject;
}
However this seems a little clunky. Is there a better way of doing
things in Cocoa that I haven't come across?
Mike.
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
40fadingred.org
This email sent to email@hidden
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden