NSThread detachNewThreadSelector锁定主线程

时间:2011-06-12 13:30:12

标签: iphone ios

我正在每60秒在后台执行一些任务。后台任务是服务器请求从网站下载文档。主要线程/ UI似乎在请求完成时锁定,我将数据保存到sqlite。

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
        [NSThread detachNewThreadSelector:@selector(startTheBackgroundSync) toTarget:self withObject:nil];
        [pool release]; 

- (void)startTheBackgroundSync {  

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];  

  //  [self performSelectorInBackground:@selector(moveSynctoBack) withObject:nil];  
  //  [self performSelectorOnMainThread:@selector(makeMyProgressBarMoving) withObject:nil waitUntilDone:NO];  

    serverSync = [[[ServerSync alloc]init]autorelease];
    while (1==1) {
        serverSync.delegate = self;
        [serverSync syncNow:nil];
        [NSThread sleepForTimeInterval:120];
    }
    [pool release];  
    [serverSync release];

}  

虽然循环没有锁定主线程,但是当ASIHTtpRequest完成数据时,它会将ui锁定一秒钟。

1 个答案:

答案 0 :(得分:4)

ASIHTTPRequest的完成选择器将始终在主线程上执行。因此,你不应该在那里做长时间的任务。

您可以安排重复的NSTimer:

,而不是启动新线程
NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:120 target:self selector:@selector(backgroundSync) userInfo:nil repeats:YES];

...使用以下操作方法:

-(void) backgroundSync
{
  ServerSync* serverSync = [[[ServerSync alloc]init]autorelease];
  serverSync.delegate = self;
  [serverSync syncNow:nil];
}

请确保您使用startAsynchronous中的ServerSync - 方法启动请求!

此外,我建议实现单例,然后使用它:

-(void)init {
   [[ServerSync sharedSync] setDelegate:self];
}

-(void) backgroundSync
{
   [[ServerSync sharedSync] syncNow];
}
相关问题