Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSArray of objects and Casting

I have a class A with a property NSString *name. If have an NSArray and add many A objects into this array, is casting necessary each time I retrieve an object? i.e.

NSString* n = (NSString*)[arr objectAtIndex:1];

Or is there a another way to do it kind of like in java where you have ArrayList<A> arr?

like image 904
bubbles Avatar asked Sep 02 '11 23:09

bubbles


1 Answers

NSArray do not store information about the types of objects contained in them. If you know for sure the types of objects in your array, you can perform a cast, either implicitly or explicitly:

NSString *n = [arr objectAtIndex:1];  // implicit type conversion (coercion) from id to NSString*
NSString *n = (NSString *)[arr objectAtIndex:1];  // explicit cast

There's no difference in runtime cost between implicit and explicit casts, it's just a matter of style. If you get the type wrong, then what is very likely going to happen is that you'll get the dreaded unrecognized selector sent to instance 0x12345678 exception.

If you have a heterogeneous array of different types of objects, you need to use the isKindOfClass: method to test the class of the object:

id obj = [arr objectAtIndex:1];
if ([obj isKindOfClass:[NSString class] ])
{
    // It's an NSString, do something with it...
    NSString *str = obj;
    ...
}
like image 99
Adam Rosenfield Avatar answered Sep 20 '22 11:09

Adam Rosenfield