Last active
August 29, 2015 14:16
-
-
Save plantpurecode/686908d873f9d210096b to your computer and use it in GitHub Desktop.
Threadsafe Mutable Dictionary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@interface JRMutableDictionary : NSMutableDictionary | |
@end | |
@implementation JRMutableDictionary { | |
dispatch_queue_t queue; | |
NSMutableDictionary *storage; | |
} | |
- (void)dealloc { | |
if(queue) { | |
dispatch_release(queue); | |
queue = NULL; | |
} | |
} | |
- (id)initWithObjects:(NSArray *)objects forKeys:(NSArray *)keys { | |
self = [super init]; | |
if(self) { | |
queue = dispatch_queue_create("JRMutableDictionaryDispatchQueue", DISPATCH_QUEUE_CONCURRENT); | |
storage = [[NSMutableDictionary alloc] initWithObjects:objects forKeys:keys]; | |
} | |
return self; | |
} | |
#pragma mark - NSDictionary | |
- (NSUInteger)count { | |
__block NSUInteger cnt = 0; | |
dispatch_sync(queue, ^{ | |
cnt = [storage count]; | |
}); | |
return cnt; | |
} | |
- (NSEnumerator *)keyEnumerator { | |
__block NSEnumerator *enumerator = nil; | |
dispatch_sync(queue, ^{ | |
enumerator = [storage keyEnumerator]; | |
}); | |
return enumerator; | |
} | |
- (id)objectForKey:(id)aKey { | |
__block id object = nil; | |
dispatch_sync(queue, ^{ | |
object = [storage objectForKey:aKey]; | |
}); | |
return object; | |
} | |
#pragma mark - NSMutableDictionary | |
- (void)setObject:(id)anObject forKey:(id)aKey { | |
dispatch_barrier_async(queue, ^{ | |
[storage setObject:anObject forKey:aKey]; | |
}); | |
} | |
- (void)removeObjectForKey:(id)aKey { | |
dispatch_barrier_async(queue, ^{ | |
[storage removeObjectForKey:aKey]; | |
}); | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment