本文介绍了通过Objective-C中的NSNotificationCenter发送和接收消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试通过Objective-C中的 NSNotificationCenter
发送和接收消息。但是,我还没有找到任何关于如何做到这一点的例子。如何通过 NSNotificationCenter
发送和接收消息?
I am attempting to send and receive messages through NSNotificationCenter
in Objective-C. However, I haven't been able to find any examples on how to do this. How do you send and receive messages through NSNotificationCenter
?
推荐答案
@implementation TestClass
- (void) dealloc
{
// If you don't remove yourself as an observer, the Notification Center
// will continue to try and send notification objects to the deallocated
// object.
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
- (id) init
{
self = [super init];
if (!self) return nil;
// Add this instance of TestClass as an observer of the TestNotification.
// We tell the notification center to inform us of "TestNotification"
// notifications using the receiveTestNotification: selector. By
// specifying object:nil, we tell the notification center that we are not
// interested in who posted the notification. If you provided an actual
// object rather than nil, the notification center will only notify you
// when the notification was posted by that particular object.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(receiveTestNotification:)
name:@"TestNotification"
object:nil];
return self;
}
- (void) receiveTestNotification:(NSNotification *) notification
{
// [notification name] should always be @"TestNotification"
// unless you use this method for observation of other notifications
// as well.
if ([[notification name] isEqualToString:@"TestNotification"])
NSLog (@"Successfully received the test notification!");
}
@end
......其他地方另一个班级...
... somewhere else in another class ...
- (void) someMethod
{
// All instances of TestClass will be notified
[[NSNotificationCenter defaultCenter]
postNotificationName:@"TestNotification"
object:self];
}
这篇关于通过Objective-C中的NSNotificationCenter发送和接收消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!