四.线程的实现方式
1.使用NSThread
//主线程默认添加自动释放池,子线程需要手动添加自动释放池否则会造成内存泄露,因为子线程管理的任务执行完后,子线程会被销毁
@autoreleasepool {
//主线程的runLoop默认开启的,子线程默认关闭.需要手动开启
//如果子线程的runloop开启,子线程就不会被销毁
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop]run];
NSLog(@"%d",[NSThread isMainThread]) ;
//获取管理方法执行的线程对象
NSThread * currentThread= [NSThread currentThread];
NSLog(@"currentThread = %@",currentThread);
//创建子线程,子线程自动进入等待启动状态
//给子线程分配任务
//第一种:(不可以得到对象)
// [NSThread detachNewThreadSelector:@selector(didClickPutAtion) toTarget:self withObject:nil];
//第二中:需要手动启动(可以得到对象)
NSThread * thread = [[NSThread alloc]initWithTarget:self selector:@selector(didClickPutAtion) object:nil];
[thread start];
[thread release];
}
2.使用NSInvocationOperation
//封装方法
NSInvocationOperation * operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(didClickPutAtion) object:nil];
//由操作对列执行程序创建子线程
NSOperationQueue * queue = [[NSOperationQueue alloc]init];
//将创建的子线程添加到队列中
[queue addOperation:operation];
[operation release];
[queue release];
3.使用NSBlockOperation
NSBlockOperation * operation = [NSBlockOperation blockOperationWithBlock:^{
//在子线程中需要执行的任务,当子线程开启运行状态时,才会执行
[self didClickPutAtion];
}];
NSOperationQueue * queue = [[NSOperationQueue alloc]init];
//最大并发数
[queue setMaxConcurrentOperationCount:10];
[queue addOperation:operation];
[queue release];
4.使用NSObject
开辟子线程执行任务
NSString * STR = @"http://pic13.nipic.com/20110313/2686941_211532129160_2.jpg";
//开辟子线程
[self performSelectorInBackground:@selector(downloadImage:) withObject:STR];
//输出当前是否处于主线程
NSLog(@"++++++++++++++%d",[NSThread isMainThread]) ;
从子线程回归主线程
-(void)downloadImage:(NSString * )URLSTRING
{
@autoreleasepool {
NSData * DATA = [NSData dataWithContentsOfURL:[NSURL URLWithString:URLSTRING]];
NSLog(@"DATA = %@",DATA);
//从子线程回家主线程
[self performSelectorOnMainThread:@selector(showImage:) withObject:DATA waitUntilDone:YES];
NSLog(@"**********%d",[NSThread isMainThread]) ;
// waitUntilDone等待子线程执行完成
}
}
//主线程中,将子线程中下载的图片显示在UIImageView
-(void)showImage:(NSData *)data
{
UIImage * image = [UIImage imageWithData:data];
}