2011-09-01 72 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代替项目中的线程。