// ViewController.m
// 通知的使用
//
// Created by yunhuihuang on 16/5/12.
// Copyright © 2016年 yhhuang. All rights reserved.
//
/*
通知实现
通知的同步,他的响应者之间同步
通知的异步如何实现,异步需要使用同步队列,在这个程序中是同步的
*/
#import "ViewController.h"
@interface ViewController (){
NSNotificationCenter *center;
NSNotification *notication1;
NSNotification *notication2;
NSNotificationQueue *queue;
NSNotificationQueue *queue1;
}
@end
@implementation ViewController
- (IBAction)btnNoticationOne:(id)sender {
[center postNotificationName:@"test1" object:nil];
NSLog(@"test1 finish");
}
- (IBAction)btnNoticationTwo:(id)sender {
[center postNotificationName:notication1 object:nil];
NSLog(@"test1 finish");
[center postNotificationName:notication2 object:nil];
NSLog(@"test2 and test1 finish");
// 将通知添加到队列中异步执行
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//初始化通知中心
center = [NSNotificationCenter defaultCenter];
//添加通知名字
notication1 = [NSNotification notificationWithName:@"test1" object:nil];
notication2 =[NSNotification notificationWithName:@"test2" object:nil];
//添加多个通知队列
queue = [NSNotificationQueue defaultQueue];
queue1 = [NSNotificationQueue defaultQueue];
[queue enqueueNotification:notication1 postingStyle:2];
[queue1 enqueueNotification:notication2 postingStyle:2];
//添加通知notication1的观察者
[center addObserver:self selector:@selector(second) name:notication1 object:nil];
[center addObserver:self selector:@selector(first) name:notication1 object:nil];
//添加通知notication2的观察者
[center addObserver:self selector:@selector(third) name:notication2 object:nil];
}
-(void)first{
NSLog(@"first");
}
-(void)second{
NSLog(@"second");
//sleep(30);
}
-(void)third{
NSLog(@"third");
}
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[center removeObserver:self];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
网友评论