Notifications in iPhone Programming

In this tutorial I will explain how local notifications can be performed in iOS application. Here there’s three important steps:

1. Create a new observer to listen for the notification (event) to happen.
2. Post the notification when our event happens.
3. Remove the observer when we no longer need it.

From apple documentation, NSNotification objects encapsulate information so that it can be broadcast to other objects by an NSNotificationCenter object. An NSNotification object (referred to as a notification) contains a name, an object, and an optional dictionary. The name is a tag identifying the notification. The object is any object that the poster of the notification wants to send to observers of that notification (typically, it is the object that posted the notification). The dictionary stores other related objects, if any. NSNotification objects are immutable objects.

NSNotificationCenter object (or simply, notification centre) provides a mechanism for broadcasting information within a program. An NSNotificationCenter object is essentially a notification dispatch table. Objects register with a notification centre to receive notifications (NSNotification objects) using the addObserver:selector:name:object: or addObserverForName:object:queue:usingBlock: methods. Each invocation of this method specifies a set of notifications. Therefore, objects may register as observers of different notification sets by calling these methods several times.

Each running Cocoa program has a default notification centre. You typically don’t create your own. An NSNotificationCenter object can deliver notifications only within a single program. If you want to post a notification to other processes or receive notifications from other processes, use an instance of NSDistributedNotificationCenter. We can create a notification object with either of the following class methods

+ (id)notificationWithName:(NSString *)aName object:(id)anObject
+ (id)notificationWithName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)userInfo



Here first method Returns a new notification object with a specified name and object. Name is the new notification name and object is the object for new notification. And the second method returns a notification object with a specified name, object, and user information. The user information dictionary for the new notification. May be nil. However, you don’t usually create your own notifications directly. The NSNotificationCenter methods will take care of that. Following methods explain the basis of observing the notification.

(void)addObserver:(id)notificationObserver selector:(SEL)notificationSelector name:(NSString *)notificationName object:(id)notificationSender
(id)addObserverForName:(NSString *)name object:(id)obj queue:(NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *))block



As per the documentation this method adds an entry to the receiver’s dispatch table with an observer, a notification selector and optional criteria: notification name and sender. Second method adds an entry to the receiver’s dispatch table with a notification queue and a block to add to the queue, and optional criteria: notification name and sender. The parameter “block” will be executed when notification is successfully posted. If a given notification triggers more than one observer block, the blocks may all be executed concurrently with respect to one another (but on their given queue or on the current thread).The following example shows how you can register to receive locale change notifications.

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
    [center addObserverForName:NSCurrentLocaleDidChangeNotification object:nil
                                                     queue:mainQueue usingBlock:^(NSNotification *note) {
                                                         
                                                         NSLog(@"The user’s locale changed to: %@", [[NSLocale currentLocale] localeIdentifier]);
                                                     }];



I will explain the above methods with the help of example. First Launch Xcode and click File > New > Project. Select an iOS Single View Application and click “Next”. Name your product “Notifications” and enter a name for your Company Identifier, such as “com.companyName.notifications.” Choose the iPhone device family and click “Next.” Choose a location to store your project and click “Create.” Open ViewController.h file, modify it as follows.

@interface ViewController : UIViewController

@property (nonatomic, strong) IBOutlet UIButton *button;

(IBAction)button:(id)sender;

@end

In the same way change the ViewController.m file as follows.

@implementation ViewController

@synthesize button;

(void)viewDidLoad
{
    [super viewDidLoad];
   
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hideButton:) name:@"buttonHide" object:nil];
}

(void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

(IBAction)button:(id)sender
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"buttonHide" object:nil];
}

(void)hideButton:(NSNotification *)notification
{
    self.button.hidden = YES;
}

@end



There are four important parts of the NSNotificationCenter method addObserver:selector:name:object:. The argument for addObserver: is the object that wants to know when a certain notification happens. The argument for selector: is the method that gets called when the notification happens. The argument for name: is the title of the notification the observer wants to know about; it must be unique. The final piece of the method is object:. Its argument is the object attached to the notification and is often nil depending on the context of the notification.

There are three important parts of the NSNotificationCenter method postNotificationName:object:userInfo:. The argument for postNotificationName: is the title of the notification that was registered in the previous addObserver:selector:name:object: method. The argument for object:, again, is the object posting the notification and in this case is nil. The argument foruserInfo is an NSDictionary that can be used to send additional information with the notification.userInfo can be nil, but in this instance we want to know the orientation of the device. In order to send it with the notification the information is packaged inside a dictionary. Now compile and run the code, the UIButton will hide after tapping on it, because button hide notification will fire.

Leave a Reply

Your email address will not be published. Required fields are marked *