iOS 通知中心 NSNotificationCenter

iOS開發中,每一個app都有一個通知中心,通知中心能夠發送和接收通知。app

在使用通知中心 NSNotificationCenter以前,先了解一下通知 NSNotification。函數

NSNotification 能夠理解爲消息對象,包含三個成員變量,以下: post

@property (readonly, copy) NSString *name;
@property (nullable, readonly, retain) id object;
@property (nullable, readonly, copy) NSDictionary *userInfo;

name:通知的名稱spa

object:針對某一個對象的通知code

userInfo:字典類型,主要是用來傳遞參數server

建立並初始化一個NSNotification能夠使用下面的方法:對象

+ (instancetype)notificationWithName:(NSString *)aName object:(nullable id)anObject;
+ (instancetype)notificationWithName:(NSString *)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;

NSNotificationCenter 通知中心,是一個單例。只能使用  [NSNotificationCenter defaultCenter] 獲取通知中心對象。blog

發送通知能夠使用下面的方法:開發

[[NSNotificationCenter defaultCenter] postNotificationName:@"testNotification" object:nil];

或者:rem

NSDictionary *userInfo = @{@"name":@"John",@"age":@"15"};
NSNotification
*notice = [NSNotification notificationWithName:@"testNotification" object:nil userInfo:userInfo]; [[NSNotificationCenter defaultCenter] postNotification:notice];

添加一個觀察者的方法(能夠理解成在某個觀察者中註冊通知):

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(haveNoti:) name:@"testNotification" object:nil];

有四個參數:第一個參數是觀察者,也就是誰註冊這個通知;第二個參數是當接收到通知時的回調函數;第三個參數是通知的名稱,通知名是區分各個通知的惟一標識;第四個參數是接收哪一個對象發過來的通知,若是爲nil,則接收任何對象發過來的該通知。

移除觀察者,兩種方法:

- (void)removeObserver:(id)observer;
- (void)removeObserver:(id)observer name:(NSString *)aName object:(id)anObject;

NSNotificationCenter 的使用舉例以下:

發送通知(兩種方法):

- (void)btnClicked
{
    //[[NSNotificationCenter defaultCenter] postNotificationName:@"testNotification" object:nil];
    
    NSDictionary *userInfo = @{@"name":@"John",@"age":@"15"};
    
    NSNotification *notice = [NSNotification notificationWithName:@"testNotification" object:nil userInfo:userInfo];
    [[NSNotificationCenter defaultCenter] postNotification:notice];
    
}

增長觀察者:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(haveNoti:) name:@"testNotification" object:nil];

回調函數(能夠利用回調函數的參數 notification得到該通知的信息,好比name、object、參數):

- (void)haveNoti:(NSNotification *)notification
{
    NSLog(@"name = %@",[notification name]);
    
    
    NSDictionary *userInfo = [notification userInfo];
    NSLog(@"info = %@",userInfo);
}

針對某一個特定對象的通知的使用場景:

UITextField,好比說咱們要監聽UITextField 裏面內容的變化,此時能夠註冊下面的通知

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchBarTextChange) name:UITextFieldTextDidChangeNotification object:self.searchBar];

self.searchBar 是 UITextField 類型。 

相關文章
相關標籤/搜索