NSThread在后台IOS中

时间:2012-04-01 01:42:50

标签: iphone ios ipad nsthread

我有一个调用新线程的计时器,这个线程调用一个正在处理pararelo的函数,但是当应用程序在后台运行一段时间后它会冻结。我的代码如下

在DidLoad中

timerMusica = [NSTimer scheduledTimerWithTimeInterval:(15) target:self selector:@selector(treadAtualizaMusica) userInfo:nil repeats:YES];

... 调用新线程的函数:

-(void)treadAtualizaMusica{
    [NSThread detachNewThreadSelector:@selector(atualizaMusica:) toTarget:self withObject:nil];
}

执行的操作:

- (void)atualizaMusica:(NSTimer *)aNotification{
    NSURL *dataUrl = [NSURL URLWithString:@"http://www.xxxxx.com.br/musica.php"];
    NSString *fileString = [NSString stringWithContentsOfURL:dataUrl encoding:NSASCIIStringEncoding error:nil];

    NSLog(@"buscando string");

    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
        if (fileString == NULL) {
            autoScrollLabel.text = [NSString stringWithFormat:@"xxxxx"];
            autoScrollLabel.textColor = [UIColor whiteColor];
            autoScrollLabel.font = [UIFont boldSystemFontOfSize:12 ];

        }
        else{
            autoScrollLabel.text = [NSString stringWithFormat:@"%@",fileString];
            autoScrollLabel.textColor = [UIColor whiteColor];
            autoScrollLabel.font = [UIFont boldSystemFontOfSize:12 ];
        } 

    }
   else{
        if (fileString == NULL) {
            scrollMusica.text = [NSString stringWithFormat:@"xxxxx"];
            scrollMusica.textColor = [UIColor whiteColor];
            scrollMusica.font = [UIFont boldSystemFontOfSize:12 ];

        }
        else{
            scrollMusica.text = [NSString stringWithFormat:@"%@",fileString];
            scrollMusica.textColor = [UIColor whiteColor];
            scrollMusica.font = [UIFont boldSystemFontOfSize:12 ];
        }
    }
}

我不知道这是否是打开新主题的正确方法,但这就是我发现的搜索结果。

我需要这个单独的线程,因为我的函数在服务器中查找字符串,并且User的连接速度很慢,应用程序在下载时被锁定。上面的代码解决了这个问题,但又创建了另一个我,正如我上面提到的,当应用程序在后台运行一段时间后会冻结。

1 个答案:

答案 0 :(得分:0)

切换任务时,iOS中没有运行后台线程 您需要获得许可继续运行一点。
使用

  

UIApplication beginBackgroundTaskWithExpirationHandler