我已经创建了一个示例应用程序。它每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