开发者

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: 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜