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.
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.
An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.
arrays can't contain nil.
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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With