Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find object of certain kind in an 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's gotta be a better way, right?

like image 300
Derrick Avatar asked Aug 22 '10 04:08

Derrick


People also ask

What's a difference between NSArray and NSSet?

The main difference is that NSArray is for an ordered collection and NSSet is for an unordered collection. There are several articles out there that talk about the difference in speed between the two, like this one. If you're iterating through an unordered collection, NSSet is great.

What is difference between NSArray and NSMutableArray?

The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.

How do you check if an array contains a value in Objective-C?

To determine if the array contains a particular instance of an object, you can test for identity rather than equality by calling the indexOfObjectIdenticalTo: method and comparing the return value to NSNotFound .

Can NSArray contain nil?

arrays can't contain nil. There is a special object, NSNull ( [NSNull null] ), that serves as a placeholder for nil.


2 Answers

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 image 153
jtbandes Avatar answered Sep 22 '22 06:09

jtbandes


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 :/

like image 27
Jorge Israel Peña Avatar answered Sep 20 '22 06:09

Jorge Israel Peña