如何在不同线程的后台执行某些操作,如果它在主线程上执行,它将阻止我的应用程序的UI。任何人有任何想法如何做到这一点?在iOS中的不同线程上执行后台任务
即使它在后台打印NSLog它会没事的。 即使用户按HOME按钮,我也想运行下面的东西。 在我的viewController我这样做:
- (IBAction)btnStartClicked:(UIButton *)sender {
[NSThread detachNewThreadSelector:@selector(StartBGTask) toTarget:self withObject:nil];
}
-(void)StartBGTask{
[[[UIApplication sharedApplication] delegate] performSelector:@selector(startThread)];
}
和appDelegate.m我有这个方法
-(void) startThread {
@autoreleasepool {
for (int i = 0; i < 100; i++) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"current progress %d", i);
});
[NSThread sleepForTimeInterval:1];
}
}
}
它输出从1到100的整数上1秒的时间间隔。
Your for(){}在主队列中执行。你使用[NSThread sleepForTimeInterval:1],是不是会阻止你的用户界面?你阻止你主队列。 –
编辑并包含更多细节,我试图执行第二种方法在不同的线程上执行,但当主页按钮被按下时,它停止后台任务。 –
为什么不使用计时器。你甚至不需要把它放在后台线程上。 – Abizern