Cocoa touch 为什么我的操作子类从未完成?
我有一个Cocoa touch 为什么我的操作子类从未完成?,cocoa-touch,key-value-observing,nsoperation,Cocoa Touch,Key Value Observing,Nsoperation,我有一个NSOperation子类,我想同时运行它 我的理解是,要使并发操作正常工作: 我需要定义isConcurrent以返回YES 我需要定义start方法 我需要发送KVOs通知,以便isExecuting和isFinished完成后执行 当isExecuting和isFinished的值更改时,使用@synthesis将自动发送适当的KVO通知 尽管如此,我已经验证了我的队列从未移动到下一个项目 以下是我的代码: @interface MyOperation() @property
NSOperation
子类,我想同时运行它
我的理解是,要使并发操作正常工作:
- 我需要定义
以返回isConcurrent
YES
- 我需要定义
方法start
- 我需要发送KVOs通知,以便
和isExecuting
完成后执行isFinished
- 当
和isExecuting
的值更改时,使用isFinished
将自动发送适当的KVO通知@synthesis
@interface MyOperation()
@property (readwrite) BOOL isExecuting;
@property (readwrite) BOOL isFinished;
@end
@implementation MyOperation
- (void)start
{
@autoreleasepool {
self.isExecuting = YES;
self.HTTPOperation = [[AFHTTPRequestOperation alloc] initWithRequest: URLRequest];
_HTTPOperation.completionBlock = [^{
[self completed];
self.isExecuting = NO;
self.isFinished = YES;
} copy];
[_HTTPOperation start];
}
}
- (BOOL)isConcurrent
{
return YES;
}
- (void)completed
{
}
@end
我错过了什么
(这是在iPhone上,但我无法想象这有什么关系。)看起来,无论KVO通知
@synthesis
发送什么,都不足以让NSOperationQueue
继续前进
手动发送通知可修复此问题:
- (void)start
{
@autoreleasepool {
[self willChangeValueForKey:@"isExecuting"];
self.isExecuting = YES;
[self didChangeValueForKey:@"isExecuting"];
NSURLRequest *URLRequest = [self buildRequest];
if (!URLRequest) {
[self willChangeValueForKey:@"isFinished"];
[self willChangeValueForKey:@"isExecuting"];
_isExecuting = NO;
_isFinished = YES;
[self didChangeValueForKey:@"isExecuting"];
[self didChangeValueForKey:@"isFinished"];
return;
}
self.HTTPOperation = [[AFHTTPRequestOperation alloc] initWithRequest: URLRequest];
_HTTPOperation.completionBlock = [^{
[self completed];
[self willChangeValueForKey:@"isFinished"];
[self willChangeValueForKey:@"isExecuting"];
_isExecuting = NO;
_isFinished = YES;
[self didChangeValueForKey:@"isExecuting"];
[self didChangeValueForKey:@"isFinished"];
} copy];
[_HTTPOperation start];
}
}
另见:
@interface MyOperation : NSOperation
@property (assign) id<MyOperationDelegate> delegate;
}
最后是你的协议
@class MyOperation;
@protocol MyOperationDelegate <NSObject>
@optional
-(void)operationComplete:(MyOperation*)operation;
-(void)operationCancelled;
@class MyOperation;
@协议代理
@可选的
-(无效)操作完成:(MyOperation*)操作;
-(无效)取消运营;
感谢您的回答,这是我对NSO操作的了解的补充。我的实际问题是@synthesis没有触发正确的KVO事件。手动控制事件修复了这一问题。
-(void)main{
[NSException exceptionWithName:kTaskException
reason:@"Only to be used with subclass"
userInfo:nil];
}
@class MyOperation;
@protocol MyOperationDelegate <NSObject>
@optional
-(void)operationComplete:(MyOperation*)operation;
-(void)operationCancelled;