Using NSNotificationCenter with Example

I was using delegate methods and custom protocols to call method of one class from another class when I was beginner to iOS development. Later I started reading about NSNotificationCenter from various articles of Apple application development and found that we can use NSNotificationCenter as an alternative to custom protocols based on requirements of business logic. Making custom protocols and registering methods is hard to do in a big project and NSNotificationCenter can free us from that burden.

NSNotificationcenter implements the observer pattern in generic way. The main idea behind NSNotificationCenter is decoupling, means that the object should know about each other as few as possible.

The main approach used with NSNotificationCenter is that any object can send a notification to the notification center and at the same time any other object can listen for notifications on that center.

Here is the example about using NSNotificationCenter…

Example

There is a method named myTestNotificationReceived which is implemented in myClassA. Now I want to call this method from another class myClassB. Below is the code how I can do this using NSNotificationCenter.

Objective-C

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

@implementationmyClassA

-(void)dealloc{

[[NSNotificationCenterdefaultCenter] removeObserver:self];

[superdealloc];

}

-(id)init

{

self=[superinit];

if(!self)returnnil;

[[NSNotificationCenterdefaultCenter] addObserver:self

selector:@selector(myTestNotificationReceived:)

name:@"myTestNotification"

object:nil];

returnself;

}

-(void) myTestNotificationReceived:(NSNotification*)notification

{

if([[notification name] isEqualToString:@"myTestNotification"])

NSLog(@"Notification is successfully received!");

}

@end

Now I want to call the method myTestNotification from myClassB.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

@implementation myClassB

-(void)dealloc{

[superdealloc];

}

-(id)init

{

self=[superinit];

if(!self)returnnil;

returnself;

}

-(void)myMethod

{

// All instances of myClassA will be notified

[[NSNotificationCenter defaultCenter]

postNotificationName:@"myTestNotification"

object:self];

}

@end

Important: It is advisable to call the removeObserver: method of NSNotificationCenter in the dealloc method to avoid crashes.

Hope this was easy to understand about NSNotificationCenter. Pl. drop your queries or suggestions.