Skip to content

Instantly share code, notes, and snippets.

@loganwright
Created May 23, 2014 23:17
Show Gist options
  • Save loganwright/eb844fdec0873182abd8 to your computer and use it in GitHub Desktop.
Save loganwright/eb844fdec0873182abd8 to your computer and use it in GitHub Desktop.
The basic outline suggested by apple when implementing a concurrent NSOperation subclass manually
//
// NSConcurrentOperation.h
// ConcurrencyPractice
//
// Created by Logan Wright on 5/23/14.
// Copyright (c) 2014 Logan Wright. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSConcurrentOperation : NSOperation
@end
//
// NSConcurrentOperation.m
// ConcurrencyPractice
//
// Created by Logan Wright on 5/23/14.
// Copyright (c) 2014 Logan Wright. All rights reserved.
//
#import "NSConcurrentOperation.h"
NSString * const KVOPropertyIsFinished = @"isFinished";
NSString * const KVOPropertyIsExecuting = @"isExecuting";
@interface NSConcurrentOperation ()
@property (nonatomic) BOOL executing;
@property (nonatomic) BOOL finished;
@end
@implementation NSConcurrentOperation
- (id)init {
self = [super init];
if (self) {
_executing = NO;
_finished = NO;
}
return self;
}
- (void)main {
@try {
// Do the main work of the operation here.
// ... your code here
// ** Do Not Write Below **
[self completeOperation];
}
@catch (NSException *exception) {
// Do not rethrow exceptions.
NSLog(@"Exception: %@", exception);
}
}
- (void)completeOperation {
[self willChangeValueForKey:KVOPropertyIsFinished];
[self willChangeValueForKey:KVOPropertyIsExecuting];
_executing = NO;
_finished = YES;
[self didChangeValueForKey:KVOPropertyIsExecuting];
[self didChangeValueForKey:KVOPropertyIsFinished];
}
- (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"];
}
#pragma mark PROPERTY GETTER OVERRIDES
- (BOOL)isConcurrent {
return YES;
}
- (BOOL)isExecuting {
return _executing;
}
- (BOOL)isFinished {
return _finished;
}
@end
@malhal
Copy link

malhal commented Jan 9, 2017

Here is the link to the Concurrency Programming Guide that contains this suggestion, hard to find nowadays.

@malhal
Copy link

malhal commented Jan 9, 2017

It's also interesting to look a the GNUStep implementation of these methods.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment