I wrote class SafeMutableDictionary inherits NSMutableDictionary.
Class implements only "primitive" methods, which must be inherits
from NSDictionary:
- (instancetype)init;
- (instancetype)initWithObjects:(const id [])objects forKeys:(const id<NSCopying>[])keys count:(NSUInteger)cnt;
- (NSUInteger)count;
- (id)objectForKey:(id)key;
- (NSEnumerator*)keyEnumerator;
and from NSMutableDictionary:
- (void)removeObjectForKey:(id)key;
- (void)setObject:(id)obj forKey:(id)key;
Thread-safety supports by using inner variable of NSMutableDictionary type, which holds all data
@interface SafeMutableDictionary () {
__strong NSMutableDictionary* _dictEmbedded;
}
and each access to it wrap with @synchronized
block.
- (id)objectForKey:(id)key{
@synchronized (_dictEmbedded) {
return [_dictEmbedded objectForKey:key];
}
}
Repo with full code in github.
But, unfortunately, I still get crashes with errors like
Collection <__NSDictionaryM: 0x16784ff0> was mutated while being enumerated.
So, I have some questions:
1) My implementation is correct? What I missed?
2) Are exists more famous and tested solutions for this?
3) What is the best practices to access container from main and bg thread concurrently?
May be it's worst practice to do such inheritance and better using original container + care of thread-safety in