http://www.cnblogs.com/ygm900/archive/2013/06/23/3151691.html
第一步:开启子线程
//开启子线程到网络上获取数据 myFirstThread = [[NSThread alloc]initWithTarget:self selector:@selector(thread1GetData) object:nil]; [myFirstThread setName:@"第一个子线程,用于获取网络数据"]; [myFirstThread start];
第二步:子线程的方法
//获取数据 -(void)thread1GetData { while (!myFirstThread.isCancelled) { // 关键 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init]; //通过接口获取数据 (字典格式) self.dic_base64TabelViewDataSource = [self getDataFromInterFace]; //将数据字典转换成可以直接显示的cellview nsma_CellViews 相当于终极数据源 self.nsma_CellViews = [self orderDataForTableViewWithDictinary: self.dic_base64TabelViewDataSource]; //用数据源 nsma_CellViews 更新用户界面 [self performSelectorOnMainThread:@selector(updateUI) withObject:nil waitUntilDone:YES]; // [NSThread sleepForTimeInterval:0.09]; //不用亦可 [pool release]; [NSThread exit]; //关键 } }
第三步:结束子线程
-(IBAction)btnBack:(id)sender { //释放内存 仅仅remove 并不会触发内存的释放 if (!(mySecondThread==nil) && !myFirstThread.isCancelled) { [myFirstThread cancel]; //等子线程结束再跳出循环 int i=0; while (!myFirstThread.isFinished){ NSLog(@"mySecondThread还没有结束 %i",i++); } } //其它操作 }