Cathy
Cathy

Reputation: 797

How to create an object of NSNotification in 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?

Upvotes: 5

Views: 4570

Answers (2)

Thomas Zoechling
Thomas Zoechling

Reputation: 34243

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.

Upvotes: 2

outis
outis

Reputation: 77400

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.

Upvotes: 7

Related Questions