• 利用performSelectorInBackground和performSelectorOnMainThread实现多线程刷新UI


    NSObject类的performSelectorOnMainThread和performSelectorInBackground可以实现简单的多线程编程技术
    1、- (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg
    创建一个线程在子线程执行,aSelector代表了新创建的线程,arg是传入的参数
    2、- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;
    该方法的作用是在主线程中,执行制定的方法(代码块)。
    参数:
    @selector就是,要定义我们要执行的方法。
    withObject:arg定义了,我们执行方法时,传入的参数对象。类型是id。(我们可以传入任何参数)
    waitUntilDone:YES指定,当前线程是否要被阻塞,直到主线程将我们制定的代码块执行完。
    注意:
    1.当前线程为主线程的时候,waitUntilDone:YES参数无效。
    2.该方法,没有返回值

    3.该方法主要用来用主线程来修改页面UI的状态。

    sample code:

     
    1. - (void)viewDidLoad  
    2. {  
    3.     [super viewDidLoad];  
    4.     // Do any additional setup after loading the view, typically from a nib.  
    5.       
    6.     _label=[[UILabel alloc] initWithFrame:CGRectMake(40, 40, 60, 40)];  
    7.     _label.textColor=[UIColor redColor];  
    8.     _label.text=@"123";  
    9.     [self.view addSubview:_label];  
    10.       
    11.     [self performSelectorInBackground:@selector(backWork) withObject:nil];  
    12. }  
    13. -(void)backWork  
    14. {  
    15.     NSLog(@"the thread is %@",[NSThread currentThread]);  
    16.     sleep(2);  
    17.     [self performSelectorOnMainThread:@selector(mainWork) withObject:nil waitUntilDone:NO];  
    18. }  
    19.   
    20. -(void)mainWork  
    21. {  
    22.     NSLog(@"the main thread is %@",[NSThread currentThread]);  
    23.   
    24.     _label.text=@"456";  
    25.     _label.textColor=[UIColor greenColor];  
    26.   
    27. }  

    执行结果:

    2014-08-19 11:03:59.101 testApp[1848:3107] the thread is <NSThread: 0x8c504a0>{name = (null), num = 2}

    2014-08-19 11:04:01.103 testApp[1848:60b] the main thread is <NSThread: 0x8c444c0>{name = (null), num = 1}

  • 相关阅读:
    投入产出分析软件研发成功
    GIS 的未来
    无比期待arcgis10
    北京市服务业空间结构研究框架
    经济普查资料开发应用的基本方法及常用的统计分析方法
    关于公共设施或公共空间的服务区分析
    打造国家级GIS 平台——来自Jack Dangermond
    MySQL的字符串函数大全
    loadrunner 将执行脚本 写到vuser_init函数中问题
    mysql 批量update操作错误解决
  • 原文地址:https://www.cnblogs.com/zhun/p/6370982.html
Copyright © 2020-2023  润新知