开发者

Why do I need to type-cast an object when sending it an "isKindOf:" message?

If I'm trying to find out if an object is a type of a certain class (or any of that class's descendants), it seems that I should use "isKindOf:"

if ([foo isKindOfClass:[bar class]]) {...}

But the compiler gives me a warning "invalid receiver type 'v开发者_StackOverflow社区oid *'".

This goes away if I cast "foo" to NSObject...or any other class! No matter what class I cast the object to, the code still works. That is, even if I do:

if ([(NSString *)foo isKindOfClass:[bar class]]) {...}

the "isKindOfClass" method still returns TRUE if and only if "foo" is of type "bar".

Am I missing something here? Shouldn't casting "foo" to another type make the logic fail? And why do I need to cast "foo" at all, since the whole point is that I'm trying to figure out what type of object it is?


I'm guessing you've declared foo as:

void* foo;

void* is not an Objective-C type, so you can't send it messages like isKindOfClass.

Declare foo like this instead:

id foo;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜