kanghua
9/27/2017 - 2:34 AM

Async NSOperation

Subclass the NSOperation

@implementation MyOperation
@synthesize executing = _executing;
@synthesize finished = _finished;

#pragma mark -
#pragma mark operation
//if need runloop for callback
+ (void) __attribute__((noreturn)) networkRequestThreadEntryPoint:(id)__unused object {
    do {
        @autoreleasepool {
            [[NSRunLoop currentRunLoop] run];
        }
    } while (YES);
}

+ (NSThread *)networkRequestThread {
    static NSThread *_networkRequestThread = nil;
    static dispatch_once_t oncePredicate;

    dispatch_once(&oncePredicate, ^{
        _networkRequestThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint:) object:nil];
        [_networkRequestThread start];
    });

    return _networkRequestThread;
}

- (BOOL)isAsynchronous
{
    return YES;
}

- (BOOL)isFinished
{
    return _finished;
}
- (void)setFinished:(BOOL)paraIsFinished
{
    if(_finished != paraIsFinished)
    {
        [self willChangeValueForKey:@"isFinished"];
        _finished = paraIsFinished;
        [self didChangeValueForKey:@"isFinished"];
    }
}

- (BOOL)isExecuting
{
    return _executing;
}
- (void)setExecuting:(BOOL)paraIsExecuting {
    if(_executing != paraIsExecuting)
    {
        [self willChangeValueForKey:@"isExecuting"];
        _executing = paraIsExecuting;
        [self didChangeValueForKey:@"isExecuting"];
    }
}
- (void)main
{
    //do main work
}
- (void)start
{
    [self main];
}

- (void)finishWork
{
    //finish work, do sth clean
    
    self.executing = NO;
    self.finished = YES;
}
@end