How to find an object of a certain kind in NSArray?

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 should be a better way, right?

+5
source share
3 answers

Block 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];

This is not exactly shorter. You can write your own method NSArrayto do this.

+10
source

As mentioned in jtbandes, you can write a method NSArrayas a category if you are going to do this a lot. Something like that:

@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 contain all the objects of the specified class.

: , , - :/

+3

. . , API iOS4, .

0

All Articles