将 NSOperation 的自定义子类标记为已终止?
我创建了 NSOperation 的自定义子类,并覆盖了 main
方法。
@interface WGTask : NSOperation
@property(readonly) BOOL isExecuting,isFinished;
@end
@implementation WGTask
@synthesize isExecuting,isFinished;
- (void)start {
...
[self willChangeValueForKey:@"isFinished"];
isFinished=YES;
[self didChangeValueForKey:@"isFinished"];
...
}
@end
但此代码会引发 EXC_BAD_ACCESS 错误。删除 [self didChangeValueForKey:@"isFinished"]
和 [self willChangeValueForKey:@"isFinished"]
可以解决问题,但即使 isFinished
值已正确更新,NSOperationQueue 不会删除该操作!
I've created a custom subclass of NSOperation and I've overwritten the main
method.
@interface WGTask : NSOperation
@property(readonly) BOOL isExecuting,isFinished;
@end
@implementation WGTask
@synthesize isExecuting,isFinished;
- (void)start {
...
[self willChangeValueForKey:@"isFinished"];
isFinished=YES;
[self didChangeValueForKey:@"isFinished"];
...
}
@end
But this code raises an EXC_BAD_ACCESS error. Removing [self didChangeValueForKey:@"isFinished"]
and [self willChangeValueForKey:@"isFinished"]
solves the problem, but even if the isFinished
value is correctly updated, the NSOperationQueue doesn't remove the operation!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要将 isExecuting 等创建为属性
来自文档:
如果您正在实现并发操作,则应该重写此方法以返回操作的执行状态。如果您确实覆盖它,请务必在操作对象的执行状态发生变化时为 isExecuting 键路径生成 KVO 通知。有关手动生成 KVO 通知的更多信息,请参阅键值观察编程指南。
实际上,您可能想使用 NSOperation
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/NSOperation_class/Reference/Reference.html
您可能还希望阅读
NS操作和键值观察
和(如果您使用这些标志进行依赖管理)
NSOperation KVO 问题
Don't create isExecuting et al as a property
From the docs:
If you are implementing a concurrent operation, you should override this method to return the execution state of your operation. If you do override it, be sure to generate KVO notifications for the isExecuting key path whenever the execution state of your operation object changes. For more information about manually generating KVO notifications, see Key-Value Observing Programming Guide.
Really, you probably want to use the cancel semantics of an NSOperation
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/NSOperation_class/Reference/Reference.html
You may also wish to read
NSoperation and key value observing
and (if you are using these flags for dependency management)
NSOperation KVO problem
我的错。在调用
[self willChangeValueForKey:@"isFinished"]
之前,我调用了自定义子类的委托方法,在该方法中我释放了任务本身。这就是为什么我收到 EXC_BAD_ACCESS 错误,因为self
不再存在。My fault. Before calling
[self willChangeValueForKey:@"isFinished"]
I was calling a delegate method of my custom subclass in which I was releasing the task itself. That's why I got the EXC_BAD_ACCESS error, becauseself
didn't exist anymore.