How to create an object of NSNotification in Objective-C?
I want to create an object of NSNotification as sa开发者_如何学Goy:
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?
From the NSNotification documentation:
You can create a notification object with the class methods
notificationWithName:object:
ornotificationWithName:object:userInfo:
. However, you don’t usually create your own notifications directly. The NSNotificationCenter methodspostNotificationName:object:
andpostNotificationName:object:userInfo:
allow you to conveniently post a notification without creating it first.
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.
精彩评论