NSNotificationCenter观察者模式

来源:互联网 发布:python 书籍推荐 编辑:程序博客网 时间:2024/06/08 06:55

NSNotificationCenter实现了观察者模式,允许应用的不同对象间以松耦合的方式进行通信。

NSNotificationCenter相当于一个消息中心,首先由Observer组件向NSNotificationCenter进行注册—表明该Observer组件对哪些NSNotification感兴趣。

当Poster向NSNotificationCenter发送NSNotification之后,所有在NSNotificationCenter上注册过的、对该NSNotification感兴趣的Observer对会被激发。

NSNotification代表Poster与Observer之间的信息载体,该对象包含如下只读属性。

  • @property (readonly, copy) NSString *name;通知的名字
  • @property (nullable, readonly, retain) id object;通知的Poster
  • @property (nullable, readonly, copy) NSDictionary *userInfo;用于携带通知的附加信息

发送通知:

  1. - (void)postNotification:(NSNotification *)notification;

  2. - (void)postNotificationName:(NSString *)aName object:(nullable id)anObject;

  3. - (void)postNotificationName:(NSString *)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;

注册通知:

  1. - (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSString *)aName object:(nullable id)anObject;
  2. - (id <NSObject>)addObserverForName:(nullable NSString *)name object:(nullable id)obj queue:(nullable NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *note))block

    使用NSNotificationCenter除了可以监听系统组件发出的通知(系统已经命名好名称)之外,也可以监听程序自己发出的通知(通知名称由自己命名)。

监听系统组件发出的通知:

- (void)viewDidLoad {    [super viewDidLoad];    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(finishLaunching) name:UIApplicationDidFinishLaunchingNotification object:[UIApplication sharedApplication]];}-(void)finishLaunching{    NSLog(@"finishLaunching");}

监听自定义通知:

- (void)viewDidLoad {    [super viewDidLoad];    UIButton* poster=[[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];    poster.backgroundColor=[UIColor redColor];    [self.view addSubview:poster];    [poster addTarget:self action:@selector(post) forControlEvents:UIControlEventTouchUpInside];    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(whenClick:) name:@"click" object:nil];}-(void)post{    NSNotification* notication=[[NSNotification alloc] initWithName:@"click" object:nil userInfo:@{@"name":@"ricky"}];    [[NSNotificationCenter defaultCenter] postNotification:notication];}-(void)whenClick:(NSNotification*)notificaton{    NSLog(@"name=%@",[notificaton.userInfo objectForKey:@"name"]);}
0 0
原创粉丝点击