码迷,mamicode.com
首页 > 编程语言 > 详细

通知与线程

时间:2015-06-18 21:29:12      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

代码:

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    /// 添加通知中心观察者
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification:) name:@"MyNotification" object:nil];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    // 创建一个子线程用于发布通知
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(postNotification) object:nil];
    [thread start];
}

// 发布通知
- (void)postNotification {
    NSLog(@"%@", [NSThread currentThread]);
    [[NSNotificationCenter defaultCenter] postNotificationName:@"MyNotification" object:nil];
}

// 接受通知
- (void)receiveNotification:(NSNotification *)notification {
    NSLog(@"%@", [NSThread currentThread]);
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"MyNotification" object:nil];
}

@end

输出:

<NSThread: 0x7f8f14083af0>{number = 2, name = (null)}
<NSThread: 0x7f8f14083af0>{number = 2, name = (null)}

结论:

在哪一个线程发布通知,就会在那一个线程调用对应通知的处理方法。

通知与线程

标签:

原文地址:http://www.cnblogs.com/loftyspirit/p/4586774.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!