利用performSelectorInBackground和performSelectorOnMainThread实现多线程

本文介绍NSObject类中的performSelectorOnMainThread和performSelectorInBackground方法,用于简单多线程编程。通过示例代码展示如何在子线程执行任务并在主线程更新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:

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    _label=[[UILabel alloc] initWithFrame:CGRectMake(40, 40, 60, 40)];
    _label.textColor=[UIColor redColor];
    _label.text=@"123";
    [self.view addSubview:_label];
    
    [self performSelectorInBackground:@selector(backWork) withObject:nil];
}
-(void)backWork
{
    NSLog(@"the thread is %@",[NSThread currentThread]);
    sleep(2);
    [self performSelectorOnMainThread:@selector(mainWork) withObject:nil waitUntilDone:NO];
}

-(void)mainWork
{
    NSLog(@"the main thread is %@",[NSThread currentThread]);

    _label.text=@"456";
    _label.textColor=[UIColor greenColor];

}
运行结果:

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}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值