Skip to content

Instantly share code, notes, and snippets.

@nh7a
Created May 28, 2014 02:29
Show Gist options
  • Save nh7a/729dfcc3f2afa5219c8b to your computer and use it in GitHub Desktop.
Save nh7a/729dfcc3f2afa5219c8b to your computer and use it in GitHub Desktop.
NSObject+AssociatedDictionary
#import <Foundation/Foundation.h>
@interface NSObject (AssociatedDictionary)
+ (NSMutableDictionary*)associatedDictionary;
- (NSMutableDictionary*)associatedDictionary;
@end
#import "NSObject+AssociatedDictionary.h"
#import <objc/runtime.h>
@implementation NSObject (AssociatedDictionary)
static NSDictionary* associatedDictionary(id object, const void* key)
{
NSMutableDictionary* dict = objc_getAssociatedObject(object, key);
if (!dict) {
dict = [NSMutableDictionary dictionaryWithCapacity:1];
objc_setAssociatedObject(object, key, dict, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
return dict;
}
+ (NSDictionary*)associatedDictionary
{
const void* key = (__bridge const void *)(self);
return associatedDictionary(self, key);
}
- (NSDictionary*)associatedDictionary
{
const void* key = @selector(associatedDictionary);
return associatedDictionary(self, key);
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment