Re: efficient searching of arrays
Re: efficient searching of arrays
- Subject: Re: efficient searching of arrays
- From: Greg Hurrell <email@hidden>
- Date: Mon, 14 Aug 2006 21:50:16 +0200
El 14/08/2006, a las 21:21, Mike Abdullah escribió:
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?
The code you post is a perfectly legitimate way of searching through
an array. You could hide some of its verbosity behind a macro
definition or even a method in a category on NSArray if you wanted.
There are also examples of enumeration macros out there on the web
(Google) that you can use to make the enumeration idiom a little more
compact. And changes in the GCC CVS suggest that Apple will be adding
a "foreach" keyword in Objective-C 2.0 anyway...
For alternatives you could consider some kind of "higher order
messaging":
http://cocoadev.com/index.pl?HigherOrderMessaging
Another option, if your objects are key-value coding compliant is to
leverage the NSArray's valueForKey: and indexOfObject: methods. For
example, the following one-liner (typed in Mail.app, not checked):
return [myArray objectAtIndex:[[myArray valueForKey:@"objectID"]
indexOfObject:[NSNumber numberWithUnsigned:204]]]
Note that that won't work if there is an object with that id in your
array; otherwise the indexOfObject: method will return NSNotFound and
when you pass that to objectAtIndex: an NSRangeException will be raised.
Now I personally would never use this approach but as an intellectual
exercise I guess it's possible.
G
_______________________________________________
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