当前位置:  开发笔记 > IOS > 正文

NSOperation中的异步方法

如何解决《NSOperation中的异步方法》经验,为你挑选了2个好方法。

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

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

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

非常感谢,

麦克风



1> Jason Moore..:

以下是一个完整的例子.在您的子类中,在异步方法完成后,调用[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



2> 小智..:

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

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


从iOS 7.0开始,应该使用`isAsynchronous`而不是`isConcurrent`.
推荐阅读
mobiledu2402851377
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有