You are viewing...

iOS: Selectors vs NSInvocation vs Method To Func Pointers

Updated on July 12, 2012 at the 07th hour
Posted under:

DISCLAIMER: All views are considered my own and you should not draw any conclusions on associates.

Building one of the features of the iOS app for my internship has been enlightening. Whenever I'd like to invoke a selector from another object I'd usually use [object performSelector:@selector(yada:)] and that's that. Apparently, yada is one of those functions that doesn't return an object. In fact it doesn't return anything at all, so at some point performing that same selector will cause a EXC_BAD_ACCESS. It is quite baffling to get this problem especially when it works. Sometimes, it is completely random (or not as consistent) if you add in a withDelay: in that performSelector statement.

Next best thing and my savior. NSInvocation. It works in a matter where it will perform your selector just as you would type in [object yada:arg1]. You need to get a method signature before you can init this guy, which is pretty easy to get [object methodSignatureForSelector:@selector(yada:)]; or you can use the class version [[object class] methodSignatureForSelector:...]. Once you have the invocation object, you can setTarget:object and setSelector:@selector(yada:), then call invoke (not performSelector, which is stupid to do at this point) but I like to check if the object responds to selector before doing this invocation object stuff.

One last way if to use the IMF object to call an instance method. You can get IMF objects from [object methodForSelector:@selector(yada:)]; Haha, out of laziness, you can read about it.
You just read "iOS: Selectors vs NSInvocation vs Method To Func Pointers". Please share if you liked it!
You can read more recent posts here.