在的NSOperation异步方法 [英] Asynchronous methods in NSOperation

查看:208
本文介绍了在的NSOperation异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从Facebook获取连接一些数据(使用FBConnect Objective-C的2.0框架),我做的一切,在一个的NSOperation。它是在的NSOperation因为我有运行以及其他几个操作,这是其中之一。

I'm fetching some data from Facebook Connect (using the FBConnect Objective-C 2.0 framework) and I'm doing all that in an NSOperation. It is in an NSOperation because I have several other operations that run as well and this is one of them.

的问题是,所有的FBConnect通话是异步的。正因为如此,所述的NSOperation的主要方法快结束并完成标记的操作。

The problem is that all the FBConnect calls are asynchronous. Because of this, the main method of the NSOperation quickly finishes and the operation is marked as completed.

有没有一些方法来克服呢?它似乎有在FBConnect没有同步选项!

Is there some way to overcome this? It would appear there are no synchronous options in FBConnect!

非常感谢,

迈克

推荐答案

下面是一个完整的例子。在你的子类,你的异步方法完成后,调用 [自completeOperation] 过渡到成品的状态。

Below is a full example. In your subclass, after your async method completes, call [self completeOperation] to transition to the finished state.

@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

这篇关于在的NSOperation异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆