[Objective-C]定时操作和火一个委托,当它需要很长的时间来告诉用户等待

发布时间: 2016/9/22 2:38:54
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我创建了 NSOperation 做一些繁重的工作背景,但我需要通知用户,当花比平常更长时间。

- (void)timerFireMethod {
    if (_TheOperationStillWorking) {
        // fire a delegate on the main thread to update the user interface...
    }
}
- (void)doSomeHeavyWork {
    _TheOperationStillWorking = YES;
    NSTimer * timer = [NSTimer timerWithTimeInterval:5000 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:NO];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

    // Some code that BLOCKS the current NSOperation that executes this function...
    _TheOperationStillWorking = NO;
}

我试过 NSTimer 类,但作为代码阻止当前线程,因为它读取同步一些大的数据来自互联网,NSTimer 不火。 有什么更好的办法来完成的如果 NSTimer 是最好的方法如何使用它?

任何帮助将不胜感激,并感谢在前进。

解决方法 1:

您可以安排从主线程计时器︰

- (void)doSomeHeavyWork {
    _TheOperationStillWorking = YES;
    [self performSelectorOnMainThread:@selector(scheduleTimer) withObject:nil waitUntilDone:NO];

    // Some code that BLOCKS the current NSOperation that executes this function...

    _TheOperationStillWorking = NO;
}

- (void)scheduleTimer {
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:5000 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:NO];
}

- (void)timerFireMethod {
    OSMemoryBarrier(); // make sure private var is up to date
    if (_TheOperationStillWorking) {
        // updates here will happen on the main thread...
    }
}

你需要的信息为什么 OSMemoryBarrier() 若要保护您的变量,请参阅此页

官方微信
官方QQ群
31647020