1-通知
2016-10-29 本文已影响37人
千秋画雪
优缺点
优点:
一对多
缺点:
观察者销毁时要从通知中心移除
使用步骤:
- 到通知中心注册观察者
- 发送通知
- 接受通知后调用方法
- 在通知中心移除观察者
//
// 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);
/**
接受通知执行方法
参数一:通知名称
参数二:传递一个参数对象
*/
[[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]) {
/**
*通知中心注册通知者
*参数一:注册观察者对象,参数不能为空
*参数二:收到通知执行的方法,可以带参
*参数三:通知的名字
*参数四:收到指定对象的通知,没有指定具体对象就写nil
*/
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification:) name:@"feed" object:nil];
}
return self;
}
// 接受通知后实现的方法
- (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;
}