0
[self performSelector:@selector(stopPulling) withObject:nil afterDelay:0.01];

代码很好。我只是认为使用 NSOperation 和 block 应该是未来的方向。

我熟悉NSOperation。我只想对块和 NSOperation 做同样的事情。

我已经可以用 GCD 做到这一点:

int64_t delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    <#code to be executed on the main queue after delay#>
});

来吧。有什么可以在 GCD 中完成而在 NSOperation 中无法更轻松地完成的事情?

4

3 回答 3

1

我最终做了这个:

#import "BGPerformDelayedBlock.h"

@implementation BGPerformDelayedBlock


+ (void)performDelayedBlock:(void (^)(void))block afterDelay:(NSTimeInterval)delay
{
    int64_t delta = (int64_t)(1.0e9 * delay);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delta), dispatch_get_main_queue(), block);
}

+(void)performSlightlyDelayedBlock:(void (^)(void))block
{
    [self performDelayedBlock:block afterDelay:.1];
}
@end

它基于如何在延迟后触发块中的答案,例如 -performSelector:withObject:afterDelay:?

我认为它不应该是一个类别。

奇怪的是我最终使用了 GCD。

但是,使用它很简单。我只是做:

    [BGPerformDelayedBlock performSlightlyDelayedBlock:^{
        [UIView animateWithDuration:.3 animations:^{
            [self snapToTheTopOfTheNonHeaderView];
        }];
    }];
于 2012-10-25T05:31:21.007 回答
1

NSOperationQueue 不提供延迟执行的机制。使用 GCD 或 NSTimer。

于 2012-10-25T05:36:41.897 回答
0

您的代码类似于NSTimer在 0.01 秒后使用设置选择器,没有重复。这将在主线程上调用。

NSOperation或块用于在后台执行操作。您可以使用这些来代替performSelectorInBackground.

如果您需要在后台工作,那就去做吧。有很多教程可以用来学习 'NSOperationusing 'NSOperationQueue和 blocks.

于 2012-10-23T06:31:37.167 回答