我正在从 Facebook Connect 获取一些数据(使用 FBConnect Objective-C 2.0 框架),并且我在 NSOperation 中完成所有这些操作。它位于 NSOperation 中,因为我还运行了其他几个操作,这就是其中之一。
问题在于所有 FBConnect 调用都是异步的。因此,NSOperation 的 main 方法很快完成,并且该操作被标记为已完成。
有什么办法可以克服这个问题吗? FBConnect 中似乎没有同步选项!
非常感谢,
迈克
最佳答案
下面是一个完整的示例。在您的子类中,异步方法完成后,调用 [selfcompleteOperation]
转换到完成状态。
@interface AsynchronousOperation()
// 'executing' and 'finished' exist in NSOperation, but are readonly
@property (atomic, assign) BOOL _executing;
@property (atomic, assign) BOOL _finished;
@end
@implementation AsynchronousOperation
- (void) start;
{
if ([self isCancelled])
{
// Move the operation to the finished state if it is canceled.
[self willChangeValueForKey:@"isFinished"];
self._finished = YES;
[self didChangeValueForKey:@"isFinished"];
return;
}
// If the operation is not canceled, begin executing the task.
[self willChangeValueForKey:@"isExecuting"];
[NSThread detachNewThreadSelector:@selector(main) toTarget:self withObject:nil];
self._executing = YES;
[self didChangeValueForKey:@"isExecuting"];
}
- (void) main;
{
if ([self isCancelled]) {
return;
}
}
- (BOOL) isAsynchronous;
{
return YES;
}
- (BOOL)isExecuting {
return self._executing;
}
- (BOOL)isFinished {
return self._finished;
}
- (void)completeOperation {
[self willChangeValueForKey:@"isFinished"];
[self willChangeValueForKey:@"isExecuting"];
self._executing = NO;
self._finished = YES;
[self didChangeValueForKey:@"isExecuting"];
[self didChangeValueForKey:@"isFinished"];
}
@end
关于iphone - NSOperation 中的异步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1596160/