ios - 在 Objective-C 中通过 NSNotificationCenter 发送和接收

我正在尝试通过 Objective-C 中的 NSNotificationCenter 发送和接收消息。但是,我无法找到任何有关如何执行此操作的示例。如何通过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

...在另一个类(class)的其他地方...

- (void) someMethod
{

    // All instances of TestClass will be notified
    [[NSNotificationCenter defaultCenter] 
        postNotificationName:@"TestNotification" 
        object:self];

}

关于ios - 在 Objective-C 中通过 NSNotificationCenter 发送和接收消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2191594/

相关文章:

objective-c - 在 Objective-C 中创建一个抽象类

ios - UITextField 文本更改事件

ios - UITableViewCell,在滑动时显示删除按钮

objective-c - 如何将 NSString 转换为 NSNumber

ios - NS前缀是什么意思?

ios - 如何以编程方式在 iPhone 上发送短信?

ios - 如何以编程方式创建基本的 UIButton?

ios - 在 ARC 下,IBOutlets 应该强还是弱?

objective-c - 在 Objective-C 中,我如何测试对象类型?

objective-c - @synthesize 与 @dynamic,有什么区别?