Reference from this post link I implemented a similar category using the same concept of using NSMutableDictionary to store the information I need. But there is one thing confuses me in the original post
- (NSMutableDictionary *)addl_associatedDictionary
{
NSMutableDictionary *res = nil;
@synchronized(self)
{
if (!(res = [self addl_associatedDictionaryPrimitive]))
{
res = [self addl_generateAssociatedDictionary];
}
}
return res;
}
I know @synchronized keyword is a protection for the mutilthread. but as i go through other examples most of then didn't use the protection. so is the protection necessary? also can i use static dispatch_once_t to replace the @synchronized? below is my code snipptes in .m file
@dynamic associatedDict;
-(void)setAssociateValue:(NSMutableDictionary*)dict
{
objc_setAssociatedObject(self, @selector(associatedDict), dict, OBJC_ASSOCIATION_RETAIN);
}
-(id)getAssociateValue
{
return objc_getAssociatedObject(self, @selector(associatedDict));
}
-(NSMutableDictionary*)associatedDict
{
NSMutableDictionary* dict=[self getAssociateValue];
if(!dict)
{
dict=[[NSMutableDictionary alloc]init];
[self setAssociatedDict:dict];
}
return dict;
}
-(void)setAssociateDict:(NSMutableDictionary *)associatedDict
{
[self setAssociatedDict:associatedDict];
}
-(id)associate_getObjectForKey:(NSString*)key
{
return self.associatedDict[key];
}
-(void)associate_setObject:(id)obj forKey:(NSString*)key
{
[self.associatedDict setObject:obj forKey:key];
}