我已經創建了一個示例應用程序。它每1秒從服務器獲取數據並更新UITableView中的結果。我已經完成了。但它迅速崩潰了我的應用程序。我所做的就是每秒致電NSTimer。在iphone中使用常規時間間隔更新tableview
timer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(MainLoop)
userInfo:nil repeats:YES];
在那個定時器函數中,我調用了NSThread函數。
-(void)MainLoop
{
if(isPreviousThreadFinished)
{
NSLog(@"Thread Opened");
isPreviousThreadFinished = NO;
[NSThread detachNewThreadSelector:@selector(MainLoopThread) toTarget:self withObject:nil];
}
}
-(void)MainLoopThread
{
MainLoopPool=[[NSAutoreleasePool alloc]init];
//Get data from the server
[self performSelectorOnMainThread:@selector(UpdateTable) withObject:nil waitUntilDone:YES];
[MainLoopPool release];
}
-(void)UpdateTable
{
[self.tableView reloadData];
isPreviousThreadFinished = YES;
NSLog(@"Thread closed");
}
它工作正常。並從服務器上正確地重新加載數據。我用viewWillDisappear
方法停止NSTimer。當我轉到上一頁時,它有時會使應用程序崩潰。在控制檯我看到錯誤如下,
bool _WebTryThreadLock(bool), 0xb2aa410: Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now...
我的代碼有什麼問題?崩潰隨機出現。
你是否在「//從服務器獲取數據」部分調用UIKit?檢查該代碼塊中使用的類的文檔是否可以安全地用於主線程以外的線程。 –
你正在做的是開始一個新的線程,然後在該線程中,你正在調用主線程來執行一些操作。不會衝突主線程的執行嗎?我不確定,但這可能是原因。 – mayuur
我從web服務調用中獲取數據(這是一個http鏈接)。 – Dinesh