Delegation and Data Source iOS
Asked Answered
W

1

5

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?

Warfield answered 19/6, 2012 at 18:56 Comment(0)
F
14

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

Fingerbreadth answered 19/6, 2012 at 19:4 Comment(3)
Thanks for explaining my first issue. I added an example to my question.Warfield
@RMDan I added an extra explanation for your second question, I hope that clears things up a bitFingerbreadth
That makes perfect sense. I am going to have to learn more about delegation but it is starting to make sense.Warfield

© 2022 - 2024 — McMap. All rights reserved.