My first instinct is to
FooType *myFoo = nil;
for (id obj in myArray) {
if ( [obj isKindOfClass:[FooType class]] ) myFoo = obj;
}
With all the goodies in Objective-C and NSArray, there's gotta be a better way, right?
My first instinct is to
FooType *myFoo = nil;
for (id obj in myArray) {
if ( [obj isKindOfClass:[FooType class]] ) myFoo = obj;
}
With all the goodies in Objective-C and NSArray, there's gotta be a better way, right?
Nope. That's how you would do it. Though there may be version that accepts a block in the new iOS4 API that might make it a little simpler.
With Blocks support (in iOS 4 or Snow Leopard):
FooType *myFoo = nil;
NSUInteger index = [myArray indexOfObjectPassingTest:^BOOL (id obj, NSUInteger idx, BOOL *stop) {
return [obj isKindOfClass:[FooType class]];
}];
if (index != NSNotFound) myFoo = [myArray objectAtIndex:index];
It's not really any shorter. You might consider writing your own NSArray
method to do so.
Like jtbandes mentioned, you can write an NSArray
method as a category if you're going to be doing this a lot. Something like this:
@interface NSArray (FindClass)
- (NSMutableArray *) findObjectsOfClass:(Class)theClass
@end
then
@implementation NSArray (FindClass)
- (NSMutableArray *) findObjectsOfClass:(Class)theClass {
NSMutableArray *results = [[NSMutableArray alloc] init];
for (id obj in self) {
if ([obj isKindOfClass:theClass])
[results addObject:obj];
}
return [results autorelease];
}
@end
then when you want to use it just do:
NSMutableArray *objects = [myArray findObjectsOfClass:[FooType class]];
which should hold all of the objects of the specified class.
Disclaimer: not tested, sorry if something's wrong :/