What is the difference between Delegate and Notification?

后端 未结 5 532
臣服心动
臣服心动 2020-12-04 10:15

What is the difference between Delegate and Notification?

I understood like delegate and protocol,

@protocol classADelegate

-(void)DelegateMethod;

         


        
5条回答
  •  一生所求
    2020-12-04 10:43

    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  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.

提交回复
热议问题