经常会遇到这样的问题——tableview中展示来自网络的图片,每一个cell中格式“图片+文字”,全部一起下载的时候容易阻塞UI线程,因此需要线程NSthread解决这个问题。
网上有很好的例子,其中一篇是 NSthread用法 http://www.cocoachina.com/bbs/simple/?t63541.html ,这篇开发讨论区中讨论了如何使用NSthread,以及谈论到dispatch_async和nsthread,dispatch_async中具体例子中为什么界面滞后的原因。
[NSThread detachNewThreadSelector:@selector(函数名) toTarget:self withObject:参数名]; withObject,这个后面的参数名是函数downloadImage后面自带的参数!要一一对应!
1)withObject带参数:
//开一个NSThread
-(void)test:(NSString *)ic{
[NSThread detachNewThreadSelector:@selector(downloadImage:) toTarget:self withObject:ic];
}
//下载图片
- (void)downloadImage:(NSString *)ic{
NSAutoreleasePool *pool =[[NSAutoreleasePool alloc] init];
if(图片为空){
网络下载图片过程
}
//回到主线程
[self performSelectorOnMainThread:@selector(updateImage) withObject:ic waitUntilDone:YES];
[pool release];
}
//完成下载图片,更新图片
-(void)updateImage{
更新图片到相应的界面的图片控件上
}
2)withObject不带参数:
//开一个NSThread
-(void)test::(NSString *)ic{
[NSThread detachNewThreadSelector:@selector(downloadImage) toTarget:self withObject:nil];
}
//执行方法
- (void)downloadImage{
NSAutoreleasePool *pool =[[NSAutoreleasePool alloc] init];
//回到主线程
[self performSelectorOnMainThread:@selector(updateImage) withObject:nil waitUntilDone:YES];
[pool release];
}
//完成下载图片,更新图片
-(void)updateImage{
}