iOS NSOperation 子类实现及并发执行
发布日期:2021-09-07 21:17:24 浏览次数:2 分类:技术文章

本文共 2170 字,大约阅读时间需要 7 分钟。

上一节《iOS NSOperation 非并发执行》中已经讲了NSOperation中系统提供的子类NSBlockOperation和NSInvocationOperation的任务的非并发执行,以及添加到NSOperationQueue中进行并发执行。这节将NSOperation 子类实现以及并发执行。
 
NSOperation非并发子类实现,只需重盖main方法,将要执行的任务放到main方法中,在main方法中要做cancel判断的,如下例:
@interface MyNonConcurrentOperation : NSOperation
@property (strong) id myData;
- (id)initWithData:(id)data;
@end
 
@implementation MyNonConcurrentOperation
- (id)initWithData:(id)data
{
    if (self = [super init])
    {
        _myData = data;
    }
    return self;
}
- (void)main
{
    @try {
        BOOL isDone = NO;
       
        while (![self isCancelled] && !isDone) {
            // Do some work and set isDone to YES when finished
        }
    }
    @catch(...) {
        // Do not rethrow exceptions.
    }
}
@end
 
 
NSOperation 并发子类实现,必须覆盖 start、isConcurrent、isExecuting和isFinished四个方法,main方法可选
@interface MyOperation : NSOperation {
    BOOL        executing;
    BOOL        finished;
}
- (void)completeOperation;
@end
@implementation MyOperation
- (id)init {
    self = [super init];
    if (self) {
        executing = NO;
        finished = NO;
    }
    return self;
}
- (BOOL)isConcurrent {
    return YES;
}
- (BOOL)isExecuting {
    return executing;
}
- (BOOL)isFinished {
    return finished;
}
- (void)start {
    // Always check for cancellation before launching the task.
    if ([self isCancelled])
    {
        // Must move the operation to the finished state if it is canceled.
        [self willChangeValueForKey:@"isFinished"];
        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];
    executing = YES;
    [self didChangeValueForKey:@"isExecuting"];
}
- (void)main {
    @try {
       
        // Do the main work of the operation here.
       
        [self completeOperation];
    }
    @catch(...) {
        // Do not rethrow exceptions.
    }
}
- (void)completeOperation {
    [self willChangeValueForKey:@"isFinished"];
    [self willChangeValueForKey:@"isExecuting"];
   
    executing = NO;
    finished = YES;
   
    [self didChangeValueForKey:@"isExecuting"];
    [self didChangeValueForKey:@"isFinished"];
}
@end
 
 
NSOperation 的属性添加了KVO机制,当我们覆盖属性的getter方法,按我们指定的状态返回,所以在状态改变时要发起KVO通知,通知监听次属性的对象。在start方法中使用NSThread 开启了新线程实现并发执行。

转载于:https://www.cnblogs.com/shuleihen/p/4377418.html

转载地址:https://blog.csdn.net/weixin_34304013/article/details/94582389 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:黄聪:buffer overflow detected问题解决及gcc-4.1安装
下一篇:简单的DOM操作

发表评论

最新留言

感谢大佬
[***.8.128.20]2024年04月23日 08时31分29秒