How is a Delegate is different from an object in cocoa…? - iphone

i want to know how Delegate is differ from object in cocoa any good articles.
Thanks.

A delegate is just object that another object sends messages to... when any event happen, so that it can handle application-specific details the original object wasn't designed for. It's a way of customizing behavior without subclassing....

Related

Need of Delegation in iPhone Development or Objective C

What is the need of delegation in iphone/ipad development or objective C?
I read so many articles on it. All were telling how to implement the concept, but no one was telling why we need to implement that, in which case we should implement it.
Suppose you want to implement Login functionality in your app ... now you won't show Login screen every time you run your app.. only when it is first started and you don't have a login and password...
So in this case..
Your app starts :
View 1 loads (default view )
You check no Login name is there..
You load a new view..(Login View ) .
User enter his details..you get your login and password...
now you want to go back to default view and load the main app with
the names the user entered in Login View....
Now you will use delegate to pass these information(login details) back to default View..so that it knows..its details. now there are many different ways to do these things...like notification and singleton classes.. but when you want to sent more than 3-4 sets of data.. it is best to use delegates
Think of all the components that iOS and Cocoa provide you with. TableViews, TextFields, PopOvers...etc.
When the developers wrote these components, they couldn't possibly know all the various implementations that us developers were going to create using these components. But we need somehow to communicate with them in a generic way.
These components use delegates. The delegate is an implementation independent way of describing some behaviour that your component can conform to.
When UITableView need to find out what is the height of the rows, the UITableView only needs to know about UITableViewDelegate. It doesn't need to know about MyTableViewController, JohnsTableViewController, BobsTableViewController... etc.
So the delegate is decoupling the component from the implementation and the type.
Decoupling is a good thing. It makes maintaing and changing code a lot easier, and makes code reusable.
Delegation is a simple and powerful pattern in which one object in a
program acts on behalf of, or in coordination with, another object.
The delegating object keeps a reference to the other object—the
delegate—and at the appropriate time sends a message to it. The
message informs the delegate of an event that the delegating object is
about to handle or has just handled. The delegate may respond to the
message by updating the appearance or state of itself or other objects
in the application, and in some cases it can return a value that
affects how an impending event is handled. The main value of
delegation is that it allows you to easily customize the behavior of
several objects in one central object.
SOURCE
Use a delegate if you want to talk to only one object. For example, a
tableView has a delegate - only one object should be responsible for
dealing with it.
Use notifications if you want to tell everyone that something has
happened. For example in low memory situations a notification is sent
telling your app that there has been a memory warning. Because lots of
objects in your app might want to lower their memory usage it's a
notification.
this was an answer posted to my question here
There are two key benefits of delegation: customizing objects without subclassing, and improving encapsulation.
Customization without subclassing is a benefit you get from many of the Cocoa and Cocoa-Touch APIs using the delegate pattern. If they didn't do so, you might have to subclass a UITableView every time you wanted to change its behavior by using different types of cells or a different data source. Instead, you just set the table view's delegate and data source to customize its behavior.
As for encapsulation, the delegate pattern helps you keep the different components of your code separate. For example, if your custom View needs to have some data, it would be bad practice to simply give it access to your Model, or even full access to your Controller. Instead, you'd probably set up some kind of delegate protocol for your View that your Controller would implement. That way your classes know no more about each other than they need to, so that changes in one part would be less likely to break others.

Problem understanding Delegating pattern & callback functions in Objective C

Can anyone simply explain delegating pattern and callback function in objective C.
Or can point to some documents (with Easy and Basic Explanation) which can make these concepts clearer to me. As i am not getting any idea about it from any book or website or (Apple Developer)references.
All the resources i have come across to understand this, makes me more confuse by using the terminology which i find hard to digest.
Any Help Appreciated.
I will try to explain the value of delegation with one example.
Say you have a table; the table will show some rows. Suppose now, you want to customize the way this table react to some event, e.g., the selection of a specific row.
One common way of doing this in OOP is subclassing a table base class and overriding some methods there.
With delegation, you don't need subclassing the table base class; rather you use the base class and tell it to "forward" some messages to some other object. This is the basic idea.
In our example, when the row is clicked, the table base class does not know what do except sending a message to one object that you specify as the delegate to carry through that action.
So, one basic advantage of delegation is that you do not need to subclass. Another advantage you have is that a delegate can act as the delegate for several other objects. Indeed, if you have a look at the generic declaration of a delegate method, you will see that the first parameter is the object that is delegating:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
so when the delegate receives the message, it knows who sent it and with which object it should interact.
The example I gave you about the table shows one kind of delegation, which I would not compare to callbacks. Anyway, delegation can be used as well as a kind of advanced calling-back-scheme.
Take the class NSURLConnection; it can be used to manage aynchronous communication.
Async communication is the typical case where callbacks are used.
With NSURLConnection, the delegate pattern is preferred; so, instead of specifying a callback (a function, which has to be a static function, or a static class method), you specify an object. This object implements the methods that a protocol defines (NSURLConnectionDelegate protocol); you can see those as a whole set of callback functions. When the NSURLConnection has some data ready, it will call a method of the interface, e.g., – connection:didReceiveResponse: to notify that it has received the response.
In such case, the point is not avoiding subclassing, rather it is a more flexible callback mechanisms (allowing for better encapsulation, basically).
I hope this helps clarifying the two concepts...
delegate noun |ˈdeligit|
A person sent or authorized to represent others, in particular an
elected representative sent to a conference.
A delegate in the Cocoa Touch frameworks such as Foundation or UIKit is a separate object instance that is entrusted to listen in to, and optionally decide behaviours on behalf of the delegator.
Take the example of UIWebView. The web view can entrust responsibility onto one delegate as long as that instance conforms to the UIWebViewDelegate protocol, that is promises to behave as the web view expects a delegate to behave.
The delegate gets called from time to time. Embedded in the delegate method names is information about what the call is about.
webView:shouldStartLoadWithRequest:navigationType: - Tells the delegate that the webview wants to load a request, and ask the delegate if it should do so.
webView:willStartLoad: - Tells the delegate that the web view will start loading a page, and it is too late to do anything (This is a hypothetical method that is not actually available, I use it as a consistent example).
webView:didFinishLoad: - Tells the delegate that the web view did load a page and it is now finished.
The value of using delegation is that you do not need to sub-class UIWebView in order to tweak how it behaves. One objkect can also serve as delegate to many different webviews, or even serve as delegate to many different kinds of classes.
A normal UIViewController subclass probably conforms to many delegate protocols, for example UITableViewDelegate to respond to selections in a table, UIActionSheetDelegate to respond to selection from an action sheet, etc.
In Objective-C they make a big deal about delegates and make it seem like they're somehow special, but they're simply objects that get called. The only difference is the way they're used: You pass a class instance pointer to some service, and it calls back through specified methods of that instance when it needs some action or data from your code (very much similar to the callback scheme used in other languages).
"Protocols" are just a way to define the methods used in a delegate arrangement. It's a "poor man's multiple inheritance" scheme, virtually identical to the "interface" concept in Java.
But because "protocols" are available, you can (but don't have to) make your delegate class the same class as, say, your view controller. This simplifies your design in many cases (data can be easily shared, etc), but it's not at all mandatory to "share" a class that way, vs using a unique class for the delegate.

What does obj.delegate=self mean?

What does it actually mean to set the delegate of a textfield?
For example: txtField.delegate = self
"In short, that you are receiving calls from the txtField. You are setting the object 'self' as the delegate for txtField."
"That means that your 'txtField' will receive events from itself
These two answers essentially mean the same thing. But seemingly contradictory. But the first makes more sense to me. I can see why a beginner gets confused, I've been there!
Basically one is the caller one is the receiver Think of it as a chef in a kitchen call his assistant to cut up some onions. In this particular case, txtField is the chef, "self" is the assistant. txtField orders self "Do this, this and this!" Like it or not the assistant has to oblige cuz he has wife and kids to feed. :)
It means that self will be the recipient of certain method calls that are made in response to actions on the text field.
In short, that you are receiving calls from the txtField. You are setting the object 'self' as the delegate for txtField.
Delegating is a programming pattern that is widely used in Objective-C.
The basic idea is let an object delegate some tasks to another object. For example, your UITextField object delegate some tasks to your view controller. In this case, your UITextField object becomes a delegating object, and the view controller the delegate of the UITextField object. The delegating object sends certain messages to its delegate in order to get necessary information, or to notify certain events, etc.
That means that your 'txtField' will receive events from itself (kind of a weird example, maybe a larger source code section could be provided?)
For some of its methods, the textfield (any object in a class using the delegation pattern) is going to try to call some other object to so that that object can customize some of the textfield's behaviors. The object that the textfield will try call is called it's delegate. The delegate is initially set to nil, so, by default, no customization happens.
If a class has a line of code like: textfield.delegate = self; then it says that this object in this class wants to get called to handle the textfield's customization for certain of the textfield's defined delegate methods.
It means the actual class where 'txtField.delegate =self' is called will receive callsbacks from events. This is often a convenient way to do things.

UITextView with multiple delegates?

I have a UITextView that points to the File's Owner as its delegate, and I have a number of the delegate functions implemented. However, I would also like to point to a second object (in this case a TextExpander object, http://www.freshblocks.com/tutorials/how-to-add-textexpander-touch-sdk-to-iphone-apps/) also as a delegate. How might this be possible? As far as I know there can only be one delegate in objective-c.
I don't know the specific of TextExpander but he delegate design pattern assumes one and only one delegate. You can't have two delegates for one object.
There are ways around this. You could designate one of the delegates as the primary delegate and implement all the methods in this class. That class could then simple call the secondary delegate for the required methods. This is the simplest approach but does result in the primary delegate becoming tightly coupled with the secondary delegate.
Another approach would be to resolve the messages dynamically and use message forwarding. You would still require the a primary/secondary delegate pattern, but instead of the primary delegate needing to implement all the methods it would simply pass all messages it doesn't respond to onto the secondary delegate. This approach means that the secondary delegate can change by adding/removing additional delegate methods without having to change the primary delegate. The key method is - (id)forwardingTargetForSelector:(SEL)sel. See Objective-C Message Forwarding for a good explanation.
It seems that they solve this in step 5, by setting [textExpander setNextDelegate:self]; before setting the textExpander object as the "primary" delegate of the view.
I don't have the code myself so I haven't tried it, though, and their documentation is... well not.
Just for information: Delegates are not an Objective-C feature, but a design pattern using though Cocoa/Cocoa-touch.
Delegate pattern allow only one object to be notified of the changes of another. The solution to have an intermediate delegate object could be an easy way of doing things.
If you want to keep your code clean and reduce the coupling you might use another pattern known as KVO (Key Value Observing). Apple provides a good guide on how to use it.
In KVO a single object, that needs to be KVC (Key Value Coding) compliant, can notify multiple objects without even knowing about it. It uses an intermediate notifier object (singleton for you application).
Check the Apple doc on KVC + KVO and you shall be able to do what you want.
I have a class with the protocol NSXMLParserDelegate implemented. I call this ParserHelper. I parse a lot of XML which happen to have some tags in all of them and i have about 20 parsers (one for each type of XML), and i didnt want to implement it over and over again.
So, I subclassed my ParserHelper class 20 times, adding in each subclass the required tags/behaviours like CaseAParser, CaseBParser and so on...
I just implement the delegate methods i needed and called it on the superclass once i'm done with the method.
I assume it works on every delegate.
This way, all you need is to make your class a subclass of SMTEDelegateController and implement the methods you need, remembering to call the [super whatEverMethod:andParameters] at the end of your functions and you should be good to go.

NSNotification vs. Delegate Protocols?

I have an iPhone application which basically is getting information from an API (in XML, but maybe JSON eventually). The result objects are typically displayed in view controllers (tables mainly).
Here is the architecture right now.
I have NSOperation classes which fetch the different objects from the remote server. Each of these NSOperation classes, will take a custom delegate method which will fire back the resulting objects as they are parsed, and then finally a method when no more results are available. So, the protocol for the delegates will be something like:
(void) ObjectTypeResult:(ObjectType *)result;
(void) ObjectTypeNoMoreResults;
I think the solution works well, but I do end up with a bunch of delegate protocols around and then my view controllers have to implement all these delegate methods. I don't think its that bad, but I'm always on the lookout for a better design.
So, I'm thinking about using NSNotifications to remove the use of the delegates. I could include the object in the userInfo part of the notification and just post objects as received, and then a final event when no more are available. Then I could just have one method in each view controller to receive all the data, even when using multiple objects in one controller.†
So, can someone share with me some pros/cons of each approach. Should I consider refactoring my code to use Events rather then the delegates? Is one better then the other in certain situations? In my scenario I'm really not looking to receive notifications in multiple places, so maybe the protocol based delegates are the way to go.
Thanks!
Actually, your design sounds sound. The clear Cocoa approach is using delegates, and is much preferred to throwing objects around. Also, defining your protocols this way makes your code very explicit and easy to understand. All in all: keep up the good work