優(yōu)缺點
優(yōu)點:
一對多
缺點:
觀察者銷毀時要從通知中心移除
使用步驟:
- 到通知中心注冊觀察者
- 發(fā)送通知
- 接受通知后調用方法
- 在通知中心移除觀察者
//
// Baby.h
#import <Foundation/Foundation.h>
@interface Baby : NSObject
@property(nonatomic,retain)NSString *name;
@property(nonatomic,retain)id nurse;
- (instancetype)init:(NSString *)name;
- (void)eat;
@end
//
// Baby.m
#import "Baby.h"
@implementation Baby
- (instancetype)init:(NSString *)name {
if (self = [super init]) {
self.name = name;
}
return self;
}
- (void)eat {
NSLog(@"%@餓了",self.name);
/**
接受通知執(zhí)行方法
參數(shù)一:通知名稱
參數(shù)二:傳遞一個參數(shù)對象
*/
[[NSNotificationCenter defaultCenter] postNotificationName:@"feed" object:self];
}
// 臨終遺言
- (void)dealloc {
NSLog(@"嬰兒睡覺了");
}
@end
//
// Nurse.h
#import <Foundation/Foundation.h>
@interface Nurse : NSObject
@end
//
// Nurse.m
#import "Nurse.h"
#import "Baby.h"
@implementation Nurse
- (instancetype)init {
if (self = [super init]) {
/**
*通知中心注冊通知者
*參數(shù)一:注冊觀察者對象,參數(shù)不能為空
*參數(shù)二:收到通知執(zhí)行的方法,可以帶參
*參數(shù)三:通知的名字
*參數(shù)四:收到指定對象的通知,沒有指定具體對象就寫nil
*/
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification:) name:@"feed" object:nil];
}
return self;
}
// 接受通知后實現(xiàn)的方法
- (void)notification:(NSNotification *)notification {
Baby *b = notification.object;
NSLog(@"給%@喂奶",b.name);
}
- (void)dealloc
{
// 從通知中心移除通知者
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"feed" object:nil];
NSLog(@"護士下班了");
}
@end
//
// main.m
#import <Foundation/Foundation.h>
#import "Baby.h"
#import "Nurse.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Baby *b = [Baby new];
Nurse *nurse = [Nurse new];
b.name = @"嬰兒";
b.nurse = nurse;
[b eat];
}
return 0;
}