经常会遇到这样的问题——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:参数名]; IcN|e4t^J+ withObject,这个后面的参数名是函数downloadImage后面自带的参数!要一一对应!
1)withObject带参数:
//开一个NSThread _nF_Rp S -(void)test:(NSString *)ic{
[NSThread detachNewThreadSelector:@selector(downloadImage:) toTarget:self withObject:ic]; IcN|e4t^J+
}
//下载图片
- (void)downloadImage:(NSString *)ic{ NSAutoreleasePool *pool =[[NSAutoreleasePool alloc] init]; `R\0g\
if(图片为空){
网络下载图片过程
} //回到主线程 2Ig.hnHj [self performSelectorOnMainThread:@selector(updateImage) withObject:ic waitUntilDone:YES]; Y,{Xv [pool release]; '<O& : } !GO4
//完成下载图片,更新图片
-(void)updateImage{
更新图片到相应的界面的图片控件上
}
2)withObject不带参数:
//开一个NSThread _nF_Rp S -(void)test::(NSString *)ic{
[NSThread detachNewThreadSelector:@selector(downloadImage) toTarget:self withObject:nil]; IcN|e4t^J+
}
//执行方法 +Z+]Tqo - (void)downloadImage LY7'wONx{ NSAutoreleasePool *pool =[[NSAutoreleasePool alloc] init]; `R\0g\ //回到主线程 2Ig.hnHj [self performSelectorOnMainThread:@selector(updateImage) withObject:nil waitUntilDone:YES]; Y,{Xv [pool release]; '<O& : }
//完成下载图片,更新图片
-(void)updateImage{
}
!GO4cbdQ
初学iphone,再次做个笔录,方便自己以后学习查看。同时希望各位前辈多指点。
转载于:https://www.cnblogs.com/asnowTT/archive/2012/05/08/2490401.html
相关资源:25个经典网站源代码