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?
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.
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.
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 .
arrays can't contain nil. There is a special object, NSNull ( [NSNull null] ), that serves as a placeholder for nil.
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 :/
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