Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an object of NSNotification in Objective-C?

Tags:

objective-c

I want to create an object of NSNotification as say:

NSNotification *obj=[[NSNotification alloc]init];

but when i create like this i get an exception as 'NSConcreteNotification init: is not allowed'. How should i solve this problem?

like image 910
Cathy Avatar asked Feb 22 '10 08:02

Cathy


People also ask

What is NSNotification?

An object containing information broadcast to registered observers that bridges to Notification ; use NSNotification when you need reference semantics or other Foundation-specific behavior.

What is NSNotification name?

A structure that defines the name of a notification.

What is Nsnotificationcenter in IOS?

A notification dispatch mechanism that enables the broadcast of information to registered observers.

How do I use NotificationCenter in Swift?

How To: Using Notification Center In Swift. With NotificationCenter you can broadcast data from one part of your app to another. It uses the Observer pattern to inform registered observers when a notification comes in, using a central dispatcher called Notification Center.


2 Answers

From the NSNotification documentation:

You can create a notification object with the class methods notificationWithName:object: or notificationWithName:object:userInfo:. However, you don’t usually create your own notifications directly. The NSNotificationCenter methods postNotificationName:object: and postNotificationName:object:userInfo: allow you to conveniently post a notification without creating it first.

like image 132
outis Avatar answered Oct 05 '22 19:10

outis


NSNotificationCenter has convenience methods to construct and dispatch notifications:

[[NSNotificationCenter defaultCenter] 
               postNotificationName:XYYourNotification
               object:@"someObject"];

If you want to use your own notifications, create the notification name extern:

extern NSString* const XYYourNotification;

and define the actual NSString* in your implementation.
If you use string constants for your notification names, your code is less error-prone to typos.

like image 33
Thomas Zoechling Avatar answered Oct 05 '22 20:10

Thomas Zoechling