在viewcontroller关闭时取消或销毁循环后台线程

时间:2016-02-17 15:31:05

标签: ios objective-c

我正在尝试为我的应用程序实现一个自动保存功能,并且当viewcontroller不再处于活动状态时遇到了解决我的后台循环问题的麻烦。

目前这是我的方法:

-(void)saveTimer{

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [NSThread sleepForTimeInterval:15];
        NSLog(@"saving now");
        [self save:self];
        [self saveTimer];
    });
}

我已经阅读了一些我可能无法取消全局线程的内容,所以我也看了这样使用NSOperationQueue:

myQueue = [[NSOperationQueue alloc] init];
    [myQueue addOperationWithBlock:^{

        // Background work

        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            // Main thread work (UI usually)
        }];
    }];

但不知道如何取消或破坏它。

2 个答案:

答案 0 :(得分:1)

我建议改用NSTimer。这样你就可以像这样启动你的计时器(持有对它的引用):

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

然后,当你想要停止它时,只需致电

[timer invalidate];
timer = nil;

答案 1 :(得分:0)

您可以在viewController的-dealloc()方法中取消operationQueue。就这样:

 (void)dealloc {
    [_queue cancelAllOperations];
    [_queue release];
}