Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2584712
  • 博文数量: 877
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 5920
  • 用 户 组: 普通用户
  • 注册时间: 2013-12-05 12:25
个人简介

技术的乐趣在于分享,欢迎多多交流,多多沟通。

文章分类

全部博文(877)

文章存档

2021年(2)

2016年(20)

2015年(471)

2014年(358)

2013年(26)

分类: iOS平台

2015-09-02 17:58:21

多线程的使用(1)-performSelectorOnMainThread
http://blog.sina.com.cn/s/blog_7b9d64af01019j2n.html
在做项目中,要提高效率,就必须使用多线程。
多线程,在网上搜索,有很多方法使用。
今天,接触到了performSelectorOnMainThread 方法。
NSAutoreleasePool *pool =[[NSAutoreleasePool alloc] init];
        [self performSelectorOnMainThread:@selector(RefreshCellForLiveId:)
                               withObject:userinfo
                            waitUntilDone:YES];
        [pool release];


该方法的作用是在主线程中,执行制定的方法(代码块)。
参数:
@selector(RefreshCellForLiveId:)就是,要定义我们要执行的方法。
withObject:userinfo
定义了,我们执行RefreshCellForLiveId:方法时,传入的参数对象。类型是id。(我们可以传入任何参数)
waitUntilDone:YES];
指定,当前线程是否要被阻塞,直到主线程将我们制定的代码块(RefreshCellForLiveId:方法)执行完。


注意:
1.当前线程为主线程的时候,waitUntilDone:YES参数无效。
2.该方法,没有返回值
3.该方法主要用来用主线程来修改页面UI的状态。
/>

利用performSelectorInBackground和performSelectorOnMainThread实现多线程

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}


阅读(407) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~