NSOperation中的异步方法

Mic*_*all 33 iphone asynchronous fbconnect nsoperation

我从Facebook Connect获取一些数据(使用FBConnect Objective-C 2.0框架),我正在NSOperation中完成所有这些工作.它在NSOperation中,因为我还运行了其他几个操作,这就是其中之一.

问题是所有FBConnect调用都是异步的.因此,NSOperation的主要方法快速完成,操作标记为已完成.

有办法克服这个问题吗?看来FBConnect中没有同步选项!

非常感谢,

麦克风

Jas*_*ore 25

以下是一个完整的例子.在您的子类中,在异步方法完成后,调用[self completeOperation]转换为已完成状态.

@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
Run Code Online (Sandbox Code Playgroud)

  • 啊。不就是不。不要定义以 _ 开头的属性。重新定义现有属性。如果需要,请调用“super”。 (2认同)

小智 6

将您的FBConnect来电置于' start',而不是' main',并管理' isFinished'' isExecuting'属性.(并返回YES' isConcurrent')

有关更多详细信息,请参阅Apple有关编写并发NSOperations的文档.

  • 从iOS 7.0开始,应该使用`isAsynchronous`而不是`isConcurrent`. (4认同)