IOS:NSNotificationCenter 消息通信

喜欢而已 提交于 2020-01-07 06:11:46

【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>

http://stackoverflow.com/questions/2191594/send-and-receive-messages-through-nsnotificationcenter-in-objective-c 给出了很好的示例:

类TestClass的实现:

@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"]) // 这个判断很有必要,其他notification name也可能执行该函数
        NSLog (@"Successfully received the test notification!");
}

@end

在另外一个类中:

- (void) someMethod
{

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

}

当调用someMethod方法时,会触发TestClass中的receiveTestNotification方法。

传递数据

如果需要传递数据,需要把receiveTestNotification修改成:

- (void) receiveTestNotification:(NSNotification *) notification

    NSDictionary *userInfo = [notification object];
}

如此触发:

NSDictionary *userInfo = [NSDictionary dictionaryWithObject:myObject forKey:@"someKey"];
    [[NSNotificationCenter defaultCenter] postNotificationName: @"TestNotification" object:userInfo];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!