Delegation and Data Source iOS

Lost Sorcerer picture Lost Sorcerer · Jun 19, 2012 · Viewed 11.5k times · Source

I have been learning about Delegation and Data Sources for iOS programming and need to ask, is there any differences that you need to do when you make a data source protocol than a delegate protocol?

Also how can I implement a delegate for many same objects in one delegate? Example one object with many unique custom alerts.

--Edit--

An example for the second part:

One object that has four different alerts each with different buttons. Since object needs to dictate how each button works by being a delegate for the alerts. How would I set the delegate methods to determine each alert?

Answer

Dan F picture Dan F · Jun 19, 2012

Both types of objects more or less behave the same way, it is a matter of what they do that is the question.

A delegate type object responds to actions that another object takes. For example, the UITableViewDelegate protocol has methods such as didSelectRowAtIndexPath for performing actions upon a user selecting a particular row in a table.

Whereas a data source type object gives data to another object. For example again, the UITableViewDataSource protocol has methods such as cellForRowAtIndexPath and numberOfRowsInSection dictating what should be displayed in the table.

There is no hard difference between the two in terms of compilation, it is simply a coding style to make what objects do what very clear to the user of the code.

EDIT:

To answer your second question: if you want each alert to respond differently, you will need to write a different delegate for each alert. For example, if one of your alerts is a save confirmation alert (perhaps you are going to overwrite a file, and it pops up to confirm thats what the user would like to do), you would have an object such as:

@interface SaveConfirmAlertDelegate : NSObject<UIAlertViewDelegate>
@end

And in the @implementation for SaveConfirmAlertDelegate you would implement the proper save feature depending on which button the user pressed in the alert.

When you create an alert view, you specify what the delegate object should be, this does not have to be self. You could have your four delegates stored as different objects and set them on the alerts as necessary.

I hope this clears things up