What is the difference between Delegate and Notification?

34,379

Solution 1

Short Answer: You can think of delegates like a telephone call. You call up your buddy and specifically want to talk to them. You can say something, and they can respond. You can talk until you hang up the phone. Delegates, in much the same way, create a link between two objects, and you don't need to know what type the delegate will be, it simply has to implement the protocol. On the other hand, NSNotifications are like a radio station. They broadcast their message to whoever is willing to listen. The radio station can't receive feedback from it's listeners (unless it has a telephone, or delegate). The listeners can ignore the message, or they can do something with it. NSNotifications allow you to send a message to any objects, but you won't have a link between them to communicate back and forth. If you need this communication, you should probably implement a delegate. Otherwise, NSNotifications are simpler and easier to use, but may get you into trouble.

Long Answer:

Delegates are usually a more appropriate way of handling things, especially if you're creating a framework for others to use. You gain compile time checking for required methods when you use protocols with your delegates, so you know when you compile if you're missing any required methods. With NSNotificationCenter you have no such guarantee.

NSNotificationCenter is kind of "hack-ish" and is frequently used novice programmers which can lead to poor architecture. A lot of times these two features are interchangeable, but more "hardcore" developers might scoff at the use of the NSNotificationCenter.


Q: what is the reason for using "id" and what is the difference of them?

A: Using id allows you to send any object to the method as a parameter. Note that you can not send primitives such as bools, floats, doubles, ints, etc. unless they are wrapped in their respective Object wrappers.


classB{

-(void)DelegateMethod;

}

and then call this in

classA{

   classB delegate;

   -(void)viewdidload{

        [self.delegate DelegateMethod];

    }

}

The above example you provided would require that classA's delegate always be of type classB, which isn't advantageous. Instead of using delegates in this scenario, you would probably just use a variable that referred to your other class, say, myClassB. The beauty of delegates is that you can pass around any object, and the code just works as long as they implement the required methods (which the compiler ensures, as long as it's marked as the correct delegate type).

Solution 2

A delegate uses protocols and creates a has-a relationship between the two classes. One of the other benefits of delegates is that you can return something back to the owning class.

Notifications, on the other hand, are more geared towards point to multipoint communication. An example of using an NSNotification might be in a tab bar controller application, where you may need to notify multiple view controllers of a particular event so they can refresh data, etc. This is great for classes that have no knowledge of one another and it wouldn't make sense if they did.

Now, to your other questions:

Why do we use id?
In your class, you want a handle to an object of indeterminate type, but which implements the protocol you define. Take UIWebView, for example. There can be infinitesimal types of classes that can be a delegate for it, therefore, it should not name a specific type of class, but specify that the class must implement the UIWebViewDelegate protocol. This reduces coupling to an absolute minimum and creates a highly cohesive application where you are creating interaction based on behavior, not state.

So, let's run through an example:

@protocol ClassADelegate
- (NSString*) determineValue;
@end

@interface ClassA : NSObject
{
    id<ClassADelegate> delegate;
}
//  Make sure you are using assign, not retain or copy
@property (nonatomic, assign) id<ClassADelegate> delegate;

@end

The implementation of ClassA:

import "ClassA.h"

@implementation ClassA
@synthesize delegate;

- (void) somePrivateMethod
{
    if (self.delegate && [self.delegate implementsProtocol:@protocol(ClassADelegate)])
    {
        NSString* value = [self.delegate determineValue];

        // Do other work
    }
}

- (void) dealloc
{
    delegate = nil;
}

@end

In the header, we declare that the class will implement the ClassADelegate protocol:

#import "ClassA.h"

@interface ClassB : NSObject <ClassADelegate>
{
}

- (void) someMethod;

@end

In the implementation of ClassB we create an instance of ClassA and set B as the delegate of A:

#import "ClassB.h"
@implementation ClassB

- (void) someMethod
{
    ClassA* aClass = [[ClassA alloc] init];

    aClass.delegate = self;

   // Other work and memory clean up of A.
   // Some logic occurs in A where it calls the delegate (self) which will 
   // call the `determineValue` method of this class.
}

//  Here's the delegate method we implement
- (NSString*) determineValue
{
    return @"I did some work!";
}

@end

Solution 3

Delegate is passing message from one object to other object. It is like one to one communication while nsnotification is like passing message to multiple objects at the same time. All other objects that have subscribed to that notification or acting observers to that notification can or can’t respond to that event. Notifications are easier but you can get into trouble by using those like bad architecture. Delegates are more frequently used and are used with help of protocols.

Solution 4

Simply We can say,

Delegates:

One - to - One

Notification:

One - to - Many

To declare Delegate

@protocol DelegateName
@required
- (void)method:(NSString *)param;
@optional
- (void)methodOptional:(NSString *)param;
@end

And declare a property for Protocol

@property id <DelegateName> delegate;

You can use

myObject.delegate = <# some object conforming to DelegateName #>;

NSNotification declaration

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(notificationHappened:)
                                             name:MyCustomNotificationName
                                           object:nil];

Then Implement

- (void)notificationHappened:(NSNotification *)notification {
    // do work here
}

You can post Notification from anywhere using,

[[NSNotificationCenter defaultCenter] postNotificationName:MyCustomNotificationName
                                                    object:self
                                                  userInfo:nil];

call removeObserver: when you are finished.

Share:
34,379
rithik
Author by

rithik

Updated on April 13, 2020

Comments

  • rithik
    rithik about 4 years

    What is the difference between Delegate and Notification?

    I understood like delegate and protocol,

    @protocol classADelegate
    
    -(void)DelegateMethod;
    
    
    @end
    
    
    
    classB <classADelegate>{
    
       classA *ObjOfclassA=[[classA alloc]init];
    
        ObjOfclassA.delegate=self;
    
    //while push later, here we have taken the pointer of classB(self) to `classA` and stored in delegate variable of classA. So, from `classA` we can call the function in `classB`
    
       push:classA from here.
    
    
       -(void)DelegateMethod{
    
            nslog(@"i am rithik from India");
    
    
         }
    
    }
    
    
    classA{
    
       id <classADelegate> delegate;
    
       -(void)viewdidload{
    
            [self.delegate DelegateMethod];
    
        }
    
    }
    

    My doubt is

    1. Why don't we use in classA like this

    classA{
    
    **classB** <classADelegate> delegate;
    
    
    [self.delegate DelegateMethod];
    
    }
    

    What is the reason for using "id" and what is the difference of them?

    2. we have call the method of classB's DelegateMethod function which is came from protocol definition.

    instead we can straightly call that method by defining that instance method of classB.because we have the got the pointer for classB in classA's delegate variable.

    like this.

    classB{
    
    -(void)DelegateMethod;
    
    }
    

    and then call this in

    classA{
    
           classB delegate;
    
           -(void)viewdidload{
    
                [self.delegate DelegateMethod];
    
            }
    
        }
    

    So, from the above we have avoided the protocol and id variable .

    but I knew many of us use delegate and protocol. Here I came to know about any advantages while use delegate and protocol

    here what is the usage of protocol implementation for method of DelegateMethod function.

    instead instance definition .

    What is the usage of those by @protocol. Please any one guide me right direction.

    I'm new to iphone developement. Right now, I knew how to create delegate. but while I came to study about the NSNotification

    That is also do the almost right job like delegate. So, when should I use the delgate or NSnotification.

  • rithik
    rithik about 13 years
    so we have to use delegate to specified known object.notification for all object .is it right
  • Matthew Frederick
    Matthew Frederick about 13 years
    I completely disagree about notifications being "hack-ish," at least by nature. Delegation is great for objects that are closely coupled or related, and is great for one-to-one communication. Notifications are for looser relationships or one-to-many communication. They can be used in a "hack-ish" way, but so can delegates.
  • rithik
    rithik about 13 years
    hey frederick the above code without use of protocol and id is right or wrong .why we have to put id variable on that..please explain ronaldo
  • rithik
    rithik about 13 years
    fred i understood very well like the color of white.thanku .but @wayne specified that we have to state in @properties with assign.is there any meaning of it.any relationship.
  • rithik
    rithik about 13 years
    Thanku so much buddy.but y we have to specify in @property with assign is there any special for this.
  • Wayne Hartman
    Wayne Hartman about 13 years
    @rithik Yes. Delegates create relationships between classes. Notifications are used to send events to one or many classes.
  • Wayne Hartman
    Wayne Hartman about 13 years
    @rithik You must assign because you aren't wanting to increase the retain count of the delegate object, nor do you want to create a copy of the instance. You just want a reference to the object in question.
  • rithik
    rithik about 13 years
    hey wayne i have to thanku so much.thanku so much.i wont forget u and fred.thanku for both of u.
  • rithik
    rithik about 13 years
    Hey the explanation about with phone example .i like very much.understood clearly.u r my best net dude .thanku for ur pain for this question.thanku thanku thanku thankuthankuthanku
  • rithik
    rithik about 13 years
    stackoverflow.com/questions/5270241/… could u please explain about this question.while i create the viewcontroller in IB the awakefromnib did not called.i want the seperate list for lifecycle of viewcontroller while creating with IB and with manual code.please explain.
  • rithik
    rithik about 13 years
    stackoverflow.com/questions/5270241/… could u please explain about this question.while i create the viewcontroller in IB the awakefromnib did not called.i want the seperate list for lifecycle of viewcontroller while creating with IB and with manual code.please explain.
  • A for Alpha
    A for Alpha over 11 years
    +1 for the Radio/phone example ;) i wish you were my teacher during my Grad days ; )
  • Exploring
    Exploring about 7 years
    @FreeAsInBeer what if I create a list of delegates and try to use it as notification? Actually I got it as a inetrview question.