Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
NSOperation subclass with customisable dispatch_queue_priority
//
// ArvoPrioritisedBlockOperation.h
// Arvo
//
// Created by James Montgomerie on 16/11/2012.
// Copyright (c) 2012 Things Made Out Of Other Things. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface ArvoPrioritisedBlockOperation : NSOperation
// Don't manipulate these after adding the operation to a queue.
@property (nonatomic, assign) dispatch_queue_priority_t dispatchPriority;
@property (nonatomic, copy) dispatch_block_t block;
- (id)initWithPriority:(dispatch_queue_priority_t)dispatchPriority
block:(dispatch_block_t)block;
@end
//
// ArvoPrioritisedBlockOperation.m
// Arvo
//
// Created by James Montgomerie on 16/11/2012.
// Copyright (c) 2012 Things Made Out Of Other Things. All rights reserved.
//
#import "ArvoPrioritisedBlockOperation.h"
#import <libkern/OSAtomic.h>
@implementation ArvoPrioritisedBlockOperation {
int32_t _isExecuting;
int32_t _isFinished;
}
- (id)initWithPriority:(dispatch_queue_priority_t)dispatchPriority
block:(dispatch_block_t)block
{
if((self = [super init])) {
_block = [block copy];
_dispatchPriority = dispatchPriority;
}
return self;
}
- (void)start
{
if(!self.isCancelled) {
[self willChangeValueForKey:@"isExecuting"];
OSAtomicCompareAndSwap32(0, 1, &_isExecuting);
[self didChangeValueForKey:@"isExecuting"];
dispatch_async(dispatch_get_global_queue(self.dispatchPriority, 0), ^{
self.block();
[self willChangeValueForKey:@"isFinished"];
[self willChangeValueForKey:@"isExecuting"];
OSAtomicCompareAndSwap32(1, 0, &_isExecuting);
OSAtomicCompareAndSwap32(0, 1, &_isFinished);
[self didChangeValueForKey:@"isExecuting"];
[self didChangeValueForKey:@"isFinished"];
});
} else {
[self willChangeValueForKey:@"isFinished"];
OSAtomicCompareAndSwap32(0, 1, &_isFinished);
[self didChangeValueForKey:@"isFinished"];
}
}
- (BOOL)isConcurrent
{
return YES;
}
- (BOOL)isExecuting
{
return OSAtomicCompareAndSwap32(1, 1, &_isExecuting);
}
- (BOOL)isFinished
{
return OSAtomicCompareAndSwap32(1, 1, &_isFinished);
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment