Cast to (id) to call an arbitrary method in Objective-C

522 Views Asked by At

I have a situation when I need to call a method not necessarily supported by the object, but at the same time I can't use performSelector because it restricts the kind of arguments you can pass to the method. Hence I do this:

if ([someObject respondsToSelector:@selector(someMethod)])
    [(id)someObject someMethod];

The compiler is happy, I am happy, but are there any caveats with this method of message sending?

What is the essential difference between the synchronous version of performSelector and the above?

Edit: is there a performance penalty with performSelector compared to the (id) method?

1

There are 1 best solutions below

11
matt On

There are no special caveats here. By casting to id you are throwing away compiler-time checking, but you were doing that anyway with performSelector:.

Note that if you are using ARC the compiler will not let you do this unless it sees some implementation of someMethod.