iOS開發————通訊方式之NSNotification

來源:互聯網
上載者:User

標籤:

NSNotification即通知,可以實現一個對象發送通知,多個對象接收到通知。


工作流程:

在需要發送通知的類中添加一個通知中樞(單例)。

在需要發送通知的類中發送通知,發送通知的對象是self,可定義相應的使用者資訊,通知名可以是任意定義的字串,監聽通知需要和此通知名匹配。

在需要接收通知的類中添加通知的接收對象,用來監聽發出的通知,下面自訂一個接收者的相應方法,方法名封裝到上面的接收對象。

最後移除當前對象監聽的通知。


舉例:在孩子這個類中發送通知,告知孩子髒了,在保姆這個類中接收通知,並實現給孩子洗澡這個方法。


#import "Child.h"@implementation Child- (instancetype)init {        if (self = [super init]) {                _cleanValue = 100;        _happyValue = 100;    }        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];        return self;}- (void)timerAction:(NSTimer *)timer {        _cleanValue--;    _happyValue--;        NSLog(@"cleanValue:%li, happyValue:%li", _cleanValue, _happyValue);        if (_cleanValue == 95) {                //擷取到通知中樞對象----單例,在記憶體中只有一個通知中樞對象        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];                        //發送通知,帶使用者資訊的通知        //使用者資訊可由可無,後面被列印出來了        NSDictionary *userInfo = @{                                   @"name" : @"tengteng",                                   @"age" : @"22"                                   };        [center postNotificationName:@"BathNotification" object:self userInfo:userInfo];            }    }@end

#import "Nanny.h"#import "Child.h"@implementation Nanny//接受到通知後針對此事件要作出響應- (instancetype)init {        if (self = [super init]) {                //監聽通知        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];                [center addObserver:self selector:@selector(cleanValueAction:) name:@"BathNotification" object:nil];    }        return self;}- (void)cleanValueAction:(NSNotification *)notification {        //保姆對小孩髒了這個事件的響應    NSLog(@"保姆給小孩洗澡");        //擷取到通知的寄件者,即小孩,這樣才能更改小孩的潔淨程度的屬性    Child *child = (Child *)notification.object;        //可以通過notification來擷取到通知寄件者傳遞的資訊    NSLog(@"userInfo:%@", notification.userInfo);        child.cleanValue = 100;}- (void)dealloc {        //移除當前對象對所有通知的監聽    [[NSNotificationCenter defaultCenter] removeObserver:self];}@end


iOS開發————通訊方式之NSNotification

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.