IOS:NSNotificationCenter 消息通讯

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

类TestClass的实现:less

@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

在另一个类中:ide

- (void) someMethod
{

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

}

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

传递数据

若是须要传递数据,须要把receiveTestNotification修改为:post

- (void) receiveTestNotification:(NSNotification *) notification

    NSDictionary *userInfo = [notification object];
}

如此触发:this

NSDictionary *userInfo = [NSDictionary dictionaryWithObject:myObject forKey:@"someKey"];
    [[NSNotificationCenter defaultCenter] postNotificationName: @"TestNotification" object:userInfo];
相关文章
相关标签/搜索