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
?
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;
...
}
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