Consider the following code:
if([obj isKindOfClass:[NSString class]]) {
NSString *s = [(NSString *)obj stringByAppendingString:@"xyzzy"];
}
I’m a bit confused here. The if statement checks whether or not obj is of the NSString class. If it is, it assigns the object and an appended string to NSString *s, do I understand this correctly? If so, why would you still cast it to (NSString *)?
Doesn’t the if statement already check for that and doesn’t that make the typecasting unnecessary?
Wouldn’t it be perfectly fine to just say:
NSString *s = obj stringByAppendingString:@"xyzzy"];
Thanks in advance.
It all depends on how
objis defined. If it isid objthen no casting is needed, but if it was defined asNSObject *objthe cast is necessary to suppress the compiler warning thatstringByAppendingString:is not defined onNSObject. The cast is not needed to make the code work at runtime, it only tells the compiler the “correct” type so it can tell whether the method should exist on the object.The reason why the cast isn’t needed for
idis becauseidmeans “an object of any type”, whileNSObject *means “an object of type NSObject”.