when I'm trying to call a method on an开发者_如何学运维 object of type id, i get a warning raised (method not found). Of course not, but isn't that the sense of an id object?
Is there a way to tell the compiler: "You don't now the class of the object on which i am calling this method, but don't worry, i'm sure it does implement it!" ?
You could use performSelector
?
And if you've got an object type id
it's probably a good idea to use respondsToSelector
as well :)
i.e.
if ([myObject respondsToSelector:@selector(dosomething:)])
myObject performSelector:@selector(doSomething:) withObject:@"hello"];
Yes, just use a variable of the proper class type. You can either perform an explicit cast when sending the message, or you can assign it to a variable of the correct type. In Objective-C, the type id
can be implicitly cast to any Objective-C object pointer type:
id myId = ...;
// Option 1: Use a cast when sending the message
[(MyClass *)myId someClassMethod];
// Option 2: Assign to a variable
MyClass *myObj = miId; // Implicit cast in the assignment
[myObj someClassMethod];
You could cast your id
object to the class you know that it is.
If you have an id
instance named instanceA
and you know that it is of ClassA
you cast it accordingly
Class A *instanceACasted = (ClassA *)instanceA;
then call the method
[instanceACasted methodCall];
精彩评论