I have been trying to figure out why and how to use performSelector. I did come across Apple Docs. However, I am not able to fully understand it. Would anyone be able to help me out in explaining this?
One usage is to work around cases where you may have collections of mixed objects that respond to different selectors. You can do things like: Code: for (NSObject *object in myCollection) { if ([object respondsToSelector:@selector(increment)]) { [object performSelector:@selector(increment)] } else if (object respondsToSelector:@selector(addOne)]) { [object performSelector:@selector(addOne)] } } So this works around the situation where some of our objects have increment and some have addOne, both of which do the same thing. You might ask why not do this: Code: for (NSObject *object in myCollection) { if ([object respondsToSelector:@selector(increment)]) { [object increment] } else if (object respondsToSelector:@selector(addOne)]) { [object addOne] } } The answer is that this will give two warnings as NSObject declares neither addOne or increment.
Happy to be corrected, but as I understand it. The second example won't work will it? Wouldn't you need to cast the id object to the class that has that method (selector) before the compiler who let it though? To me it seems to be used a lot when your sending messages to a delegate object of your class or other instances where the object sending the message doesn't doesn't need to care about the class of the receiving object other than to send that message. Like sending the Target to a UIButtonBarItem. Using a @selector the Button doesn't need to know anything else about the object it's sending the message to.
One technique is to use a protocol. I believe the declaration syntax looks something like Code: id <SomeDelegateProtocolName> theDelegate; This will tell the compiler that theDelegate is assumed to implement the methods defined by the SomeDelegateProtocolName (which you have defined and imported). You would still have to check theDelegate for method implementation, but typically only for methods you have not specified as required (in theory, at least).
Depends on whether you have warnings set as errors. It will generate a compile-time warning so it will compile and should actually execute OK.
It's just another way to send messages to objects. But more wordy because it allows choosing or creating or modifying the message at runtime, instead of just compiling it in inline and unchangeable. Can also be used to send the message to the object in another thread, for instance from a background thread, where most UI ops are illegal, back to the main UI thread.