美文网首页
多线程技术:NSOperation 与 NSOperationQ

多线程技术:NSOperation 与 NSOperationQ

作者: dc630f46ee2d | 来源:发表于2017-11-03 23:04 被阅读0次

    重写start方法来自定义NSOpeartion

    1. 子类化视图控制器
    @interface MyOperation : NSOperation
    
    @end
    
    1. 子类为原来的executing属性和finished属性添加setter方法和设置属性名
    @interface MyOperation()
    @property (assign, readonly, getter=isExecuting) BOOL executing;
    @property (assign, readonly, getter=isFinished) BOOL finished;
    @end
    
    @implementation MyOperation
    @synthesize executing = _executing;
    @synthesize finished = _finished;
    @end
    
    1. 重写setter方法,手动发送kvo监听executing的getter方法isExecutingfinishedisFinished
    - (void)setFinished:(BOOL)finished {
        [self willChangeValueForKey:@"isFinished"];
        _finished = finished;
        [self didChangeValueForKey:@"isFinished"];
    }
    
    - (void)setExecuting:(BOOL)executing {
        [self willChangeValueForKey:@"isExecuting"];
        _executing = executing;
        [self didChangeValueForKey:@"isExecuting"];
    
    
    }
    

    4.开始执行的时候设置 self.finished = NO; self.executing = YES; 结束的时候设置 self.finished = YES; self.executing = NO

    5.和main方法一样,添加self.isCanceled判断

    Demo

    #import "MyOperation.h"
    @interface MyOperation()
    @property (assign, readonly, getter=isExecuting) BOOL executing;
    @property (assign, readonly, getter=isFinished) BOOL finished;
    @end
    
    @implementation MyOperation
    
    @synthesize executing = _executing;
    @synthesize finished = _finished;
    
    - (void)start {
        if (self.isCancelled) {
            self.finished = YES;
            self.executing = NO;
        }
        self.finished = NO;
        self.executing = YES;
        [self doSomething];
    
    }
    
    - (void)doSomething {
        for (NSInteger i = 0; i < 100; i++) {
            NSLog(@"%ld", i);
        }
        self.finished = YES;
        self.executing = NO;
    
    }
    
    - (void)setFinished:(BOOL)finished {
        [self willChangeValueForKey:@"isFinished"];
        _finished = finished;
        [self didChangeValueForKey:@"isFinished"];
    }
    
    - (void)setExecuting:(BOOL)executing {
        [self willChangeValueForKey:@"isExecuting"];
        _executing = executing;
        [self didChangeValueForKey:@"isExecuting"];
    
    
    }
    @end
    

    start与main方法区别

    前者比后者更加灵活,通过operation标记状态来告知queue是否要将自己移除,在start中开了新线程后,可以在新线程的方法中标记状态。而main一定是main```执行完后自动从队列中移除。

    相关文章

      网友评论

          本文标题:多线程技术:NSOperation 与 NSOperationQ

          本文链接:https://www.haomeiwen.com/subject/pypxmxtx.html