微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

NSThread detachNewThreadSelector锁定主线程

如何解决NSThread detachNewThreadSelector锁定主线程

| 我正在每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的完成选择器将始终在主线程上执行。因此,您不应该在那里长期运行任务。 除了启动新线程,您还可以计划重复的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];
}
确保使用
ServerSync
中的
startAsynchronous
方法来启动请求! 此外,我建议实现一个单例,然后像这样使用它:
-(void)init {
   [[ServerSync sharedSync] setDelegate:self];
}

-(void) backgroundSync
{
   [[ServerSync sharedSync] syncNow];
}
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。