Skip to content

Instantly share code, notes, and snippets.

@Tricertops
Last active July 16, 2017 16:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Tricertops/e56e251fa309f3bab701 to your computer and use it in GitHub Desktop.
Save Tricertops/e56e251fa309f3bab701 to your computer and use it in GitHub Desktop.
Simple and effective thread-safe proxy that forwards all method invocations inside a locked scope. Definitely not the fastest thread-safe implementation ever.
@import Foundation;
@interface NSObject (ThreadSafeProxy)
- (instancetype)threadSafe;
@end
@interface ThreadSafeProxy : NSProxy
- (instancetype)initWithObject:(NSObject *)underlaying;
@property (readonly) NSObject *underlaying;
@property (readonly) NSRecursiveLock *lock;
@end
#import "ThreadSafeProxy.h"
@implementation ThreadSafeProxy
- (instancetype)initWithObject:(NSObject *)underlaying {
self->_underlaying = underlaying;
self->_lock = [NSRecursiveLock new];
return self;
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector {
return [self->_underlaying methodSignatureForSelector:selector];
}
- (void)forwardInvocation:(NSInvocation *)invocation {
[self->_lock lock];
[invocation invokeWithTarget:self->_underlaying];
[self->_lock unlock];
}
@end
@implementation NSObject (ThreadSafeProxy)
- (instancetype)threadSafe {
return (typeof(self))[[ThreadSafeProxy alloc] initWithObject:self];
}
@end
NSMutableArray *processedArray = [[NSMutableArray new] threadSafe];
[existingArray enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id object, NSUInteger idx, BOOL *stop) {
// ... concurrent processing ...
[processedArray addObject:object];
}];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment