2011-09-01 27 views
1

我已經創建了一個示例應用程序。它每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... 

我的代碼有什麼問題?崩潰隨機出現。

+0

你是否在「//從服務器獲取數據」部分調用UIKit?檢查該代碼塊中使用的類的文檔是否可以安全地用於主線程以外的線程。 –

+0

你正在做的是開始一個新的線程,然後在該線程中,你正在調用主線程來執行一些操作。不會衝突主線程的執行嗎?我不確定,但這可能是原因。 – mayuur

+0

我從web服務調用中獲取數據(這是一個http鏈接)。 – Dinesh

回答

0

當我在我的應用程序上工作時,我發現很好的東西 - NSOperation。它是線程安全的。您可以簡單地將您的操作添加到隊列中,而不用擔心崩潰。有一個大約的NSOperation

http://www.icodeblog.com/2010/03/04/iphone-coding-turbo-charging-your-apps-with-nsoperation/ http://www.cimgf.com/2008/02/16/cocoa-tutorial-nsoperation-and-nsoperationqueue/

我強烈建議你使用的NSOperation很多教程-s代替項目中的線程。