can any body explain in simple terms what are selectors and delegates
Joined: Aug 11, 2010
i have studied java and now trying to learn iPhone development can any one explain what is this thing selectors and delegates why they are used so much in objective c, please explain in simple examples
In Objective-C, the term for a method name is a selector, which is a SEL value type. You can either create a selector using the @selector() syntax, or you can use the NSSelectorFromString() function.
Delegate is responsible for the behavior of a UI element, it contains the logic that controls the flow of information, like saving or displaying data, and which view is seen when.
And it can be in same object as the datasource, but has its own specific protocols.
Actually delegates aren't just for UI. They are used a lot in UI, but it really is simply the GOF Delegate design pattern.
It is easier to explain in terms of UI widgets. SO that is what I am going to do. But you can have delegates anywhere.
You have a TableView that displays data. The TableView class should only be responsible for doing the view. Getting what the data is, responding to touches or other events is not its responsibility. Instead it is going to delegate responsibility to another class. The cool thing with delegates as opposed to say using an interface or inheritence is that the other class can be any class of any type.
So I take any other class and add methods to it. In the tableview class I would set its delegate property to this other class. Now in the tableview it has code in it that calls [delegate runDelegateMethod]; And everything runs.
For tableviews there are actually two types of delegates you can make and should make, one is the UITableViewDataSourceDelegate and the other is the UITableViewDelegate. I can have any class implement the methods in these delegate interfaces. So that other class has those methods defined in the interface and the other class is set as the delegate to the tableview and magic happens and it all works.
selectors are just Reflection like ways to call a method. So you can think in terms of SEL == Method in reflection. That is the quick simple description.