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?
NSArraydo 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: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 0x12345678exception.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: