Possible Duplicate:
what is this weird code notation mean
I have previously asked this question…
Understanding memory management in ios
The one thing that that line of questioning didnt teach me is what does the (NSArray *) do in the following statement:
NSArray *myArray = (NSArray *)[someNSSet allObjects];
Why isnt it just:
NSArray *myArray = [someNSSet allObjects];
or put another way, how do the two statements differ in what they do? At the moment I dont understand the (NSArray *) bit so I just ignore it and to me they look the same!
Thanks in advance
It’s a typecast, which says “convert the return value to this type”†. It’s pointless in Objective-C since
idconverts to and from any other object pointer type, but some other languages require a lot more casts, so some people do it out of habit, and others just do it because they really, really like explicitness.I would generally advise against this, because on the rare occasion that you are doing something wrong (e.g. the method returns an
NSString*and you’re assigning it to anNSArray*), this will suppress the compiler’s warning. And as noted above, if the method does return a compatible type, you don’t need to do this. So doing this blindly can only hurt you in Objective-C.† Note about casting: When you cast pointers, which includes all Objective-C object types, you don’t actually change the type of the thing that the pointer references, only the pointer itself. So you can’t change one type of object into another this way. If you cast an
NSString*to anNSDictionary*, the object is still an NSString — you’ve just lied to the compiler about it, so it won’t warn you when you try to callallKeys, and instead your program will just blow up at runtime.