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];
相關文章
相關標籤/搜索