Wednesday, 1 February 2017

NSNotificationCenter in C & Swift

NSNotificationCenter in C & Swift



For Objective C :-


Send(Post) Notification:

[[NSNotificationCenter defaultCenter] postNotificationName:@"Restorepayment" object:self];



Remove Notification:

 [[NSNotificationCenter defaultCenter] removeObserver:self name:@"Restorepayment" object:nil];



Receive(Get) Notification:


 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(check:) name:@"Restorepayment" object:nil];



Method handler for received Notification :-

-(void)check:(NSNotification *)notification
{
    if ([[notification name] isEqualToString:@"Restorepayment"])
    {

        // Your Coding
    }
}






For Swift :-


Send(Post) Notification:

NotificationCenter.default.post(name: NSNotification.Name(rawValue: "NotificationIdentifier"), object: nil)


Remove Notification:


NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "NotificationIdentifier"), object: nil)

NotificationCenter.default.removeObserver(self) // Remove from all notifications being observed
        


Receive(Get) Notification:


NotificationCenter.default.addObserver(self, selector: #selector(self.methodOfReceivedNotification(notification:)), name: Notification.Name("NotificationIdentifier"), object: nil)


Method handler for received Notification :-


func methodOfReceivedNotification(notification: Notification){
        //Take Action on Notification
        
  
        print("Notification Method Call")
    }