NSNotification & NSNotification​Center in Swift.

An NSNotificationCenter object which is provide the mechanism of broadcasting information between two class in the program. It means we can broadcast the information like object and dictionary between two class. and also calling a method of another class using NSNotificationCenter.



This tutorials include, How to register notification, Post notification and Receive notification.  

Step 1 : Adding Notification Observer to receive the notification data or broadcast information from another class.  Adding this observer in ViewDidLoad of Class A.

Adding Notification Observer Class A:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "getBloodValue:", name: "BloodValue", object: nil)

Step 2 : The method getBloodValue in which received the data or information calling to the same Class A. 

Add Notification Method  Class A:
func getBloodValue(noty : NSNotification){
    print(noty.object)
    print(noty.userInfo)
}

Step 3 : Now finally, Calling the postNotificationName method in ViewDidLoad in Class B With object Nil. Then notification Called the Class A method getBloodValue and get value as Nil because Passing an object Nil. Here define three way to PostingNotification.

Posting Notification with Nil object:
NSNotificationCenter.defaultCenter().postNotificationName("BloodValue", object: nil)
Posting Notification with B+ object:
NSNotificationCenter.defaultCenter().postNotificationName("BloodValue", object: "B+")
Posting Notification with B+ object and Dictionary:
NSNotificationCenter.defaultCenter().postNotificationName("BloodValue", object: "B+", userInfo: ["Percentage" : 8.5 , "Liter" : 4.5 , "BloodGroup" : "B+"])
Calling above postNotificationName method, You get the object and dictionary value in getBloodValue as below.


Optional(B+)

Optional([Liter: 4.5, Percentage: 8.5, BloodGroup: B+])

Step 4 : Finally after user of the Notification observer, Have to remove before the deallocated. 

Remove Notification Observers from Class A:
NSNotificationCenter.defaultCenter().removeObserver(self)
Remove Notification Observer with Name from Class A:
NSNotificationCenter.defaultCenter().removeObserver(self, name: "BloodValue", object: nil)

Thanks.
        
NSNotification & NSNotification​Center in Swift. NSNotification & NSNotification​Center in Swift. Reviewed by KIRIT MODI on 02:04:00 Rating: 5

No comments:

Powered by Blogger.