美文网首页
Delegate/Block/NSNotification与多线

Delegate/Block/NSNotification与多线

作者: 无边小猪 | 来源:发表于2016-09-02 18:20 被阅读0次

    Delegate/Block/NSNotification是最常用的事件同步方法,各自特点、区别、使用方法就不赘述了。

    下面主要想强调一下再多线程中使用Delegate/Block/NSNotification的注意事项。

    开发时Delegate的调用方法、Block的调用方法、NSNotification的post方法都可能会在非主线程中调用,此时Delegate/Block/NSNotification的回调方法也将被这个非主线程调用,尤其是Delegate的实现方法很少有人会考虑内部的多线程实现,比如更新UI。由于Delegate/Block/NSNotification可能同时在主线程和非主线程中使用,所以实现时必须同时考虑两种情况。例如更新UI的部分需要写成下面的样子:

    
    dispatch_async(dispatch_get_main_queue(),^{
    
        UIButton*button =    [[UIButtonalloc]initWithFrame:CGRectMake(50,50,100,44)];
    
        [self.viewaddSubview:button];
    
        [buttonrelease];
    
    });
    
    

    如果很不幸写成了

    
    dispatch_sync(dispatch_get_main_queue(),^{
    
        UIButton*button =  [[UIButtonalloc]initWithFrame:CGRectMake(50,50,100,44)];
    
        [self.viewaddSubview:button];
    
        [buttonrelease];
    
    });
    
    

    那么在主线程调用的时候就完了。。。没有然后了。。。

    如果是大型项目你真心不知道别人会干嘛。。。

    如果是小型项目你怎么知道以后不会发展成大项目。。。

    所以还是注意点吧!

    相关文章

      网友评论

          本文标题:Delegate/Block/NSNotification与多线

          本文链接:https://www.haomeiwen.com/subject/ckckettx.html