第一步:開啟子線程
//開啟子線程到網絡上獲取數據 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++); } } //其它操作 }
疑問:
第二步中,while方法的工作原理是什么?