开发者

Basic Objective-C typecasting question

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 app开发者_JS百科ended 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 obj is defined. If it is id obj then no casting is needed, but if it was defined as NSObject *obj the cast is necessary to suppress the compiler warning that stringByAppendingString: is not defined on NSObject. 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 id is because id means "an object of any type", while NSObject * means "an object of type NSObject".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜