【问题标题】:NSOperation accessing isCancelled in mainNSOperation 在 main 中访问 isCancelled
【发布时间】:2014-10-29 09:59:59
【问题描述】:

当前状态

我创建了一个自定义NSOperation 对象,我想在它被取消时更新一些数据。

我遵循了this answer 中所说的内容,但我没有覆盖cancel 方法。

这是我的标题:

// MyOperation.h
@interface MyOperation : NSOperation {
}
@property (nonatomic, retain) OtherDataClass *dataClass;
@end

以及实现

// MyOperation.m
@implementation MyOperation

@synthesize dataClass;

- (void)main {
    if ([self isCancelled]) {

        [self.dataClass setStatusCanceled];

        NSLog(@"Operation cancelled");
    }

    // Do some work here
    NSLog(@"Working... working....")

    [self.dataClass setStatusFinished];

    NSLog(@"Operation finished");
}

@end

问题

我在一个队列中有几个操作。我期待,当我在队列中调用 cancelAllOperations 时,我会在日志中获得 “Operation cancelled” 文本,并且在我的其他类中更新了状态,但它不起作用。队列中的操作没有调用main 方法。

为什么会发生这种情况,我该如何解决?

注意事项

我试图用这个覆盖cancel 方法:

- (void)cancel {
    [super cancel];
    [self.dataClass setStatusCanceled];
    NSLog(@"Operation cancelled");
}

它正在工作,但我读过这个方法不应该被覆盖。

【问题讨论】:

  • 我不明白为什么会再次调用main?即你开始你的 NSOperation main 被调用并做它的事情。调用cancelAllOperations 不会再次调用main,因为这只会再次开始“工作”?我在文档中没有看到任何说明您不应覆盖 cancel 的内容。能给个参考吗。
  • 我不想多次致电main。例如,我在一个队列中有 5 个操作。如果我在计算第三个时调用cancelAllOperations,我希望获得前两个和当前一个(完成时)的“操作完成”,然后是“操作取消” i> 最后两个的文本。但是我没有得到最后两行日志,因为一旦队列被取消,最后两行似乎不会调用main。关于覆盖 cancel 方法,我在 StackOverflow 的几个答案中看到了它。

标签: ios objective-c xcode nsoperation


【解决方案1】:

当您调用cancelAllOperations 时,已经开始的操作会将isCancelled 设置为YES。尚未开始的操作将不会开始。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多