English 中文(简体)
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 void * ".

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;




相关问题
Having many stacks with different types

I m making a C program that needs to use two stacks. One needs to hold chars, the other needs to hold doubles. I have two structs, node and stack: struct node { double value; struct node *...

Creating (boxed) primitive instance when the class is known

I need a method that returns an instance of the supplied class type. Let s assume that the supplied types are limited to such that an "empty" instance of them can be created. For instance, supplying ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

How to generate an instance of an unknown type at runtime?

i ve got the following in C#: string typename = "System.Int32"; string value = "4"; theses two strings should be taken to generate an object of the specified type with the specified value... result ...

Type reference scope

I m studying databases and am currently working on a object-relational DB project and I ve encountered a small problem with the number of possible constraints in an object table. I m using "Database ...

热门标签