Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an NSArray contains an object of a particular class?

Tags:

What is the best way to test if an NSArray contains an object of a certain type of class? containsObject: seems to test for equality, whereas I'm looking for isKindOfClass: equality checking.

like image 278
Dan Avatar asked Sep 06 '11 00:09

Dan


People also ask

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.

What is NSArray Objective C?

An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.

Can NSArray contain nil?

arrays can't contain nil.

Is NSArray ordered?

The answer is yes, the order of the elements of an array will be maintained - because an array is an ordered collection of items, just like a string is an ordered sequence of characters...


1 Answers

You could use blocks based enumeration to do this as well.

// This will eventually contain the index of the object.
// Initialize it to NSNotFound so you can check the results after the block has run.
__block NSInteger foundIndex = NSNotFound;

[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    if ([obj isKindOfClass:[MyClass class]]) {
        foundIndex = idx;
        // stop the enumeration
        *stop = YES;
    }
}];

if (foundIndex != NSNotFound) {
    // You've found the first object of that class in the array
}

If you have more than one object of this kind of class in your array, you'll have to tweak the example a bit, but this should give you an idea of what you can do.

An advantage of this over fast enumeration is that it allows you to also return the index of the object. Also if you used enumerateObjectsWithOptions:usingBlock: you could set options to search this concurrently, so you get threaded enumeration for free, or choose whether to search the array in reverse.

The block based API are more flexible. Although they look new and complicated, they are easy to pick up once you start using them - and then you start to see opportunities to use them everywhere.

like image 142
Abizern Avatar answered Sep 22 '22 16:09

Abizern