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