开发者

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

开发者 https://www.devze.com 2022-12-21 07:34 出处:网络
I want to create an object of NSNotification as sa开发者_如何学Goy: NSNotification *obj=[[NSNotification alloc]init];

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

精彩评论

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