Skip to content

Instantly share code, notes, and snippets.

@SmallBlackCat
Forked from maciekish/NSObject+Association.h
Last active August 29, 2015 14:13
Show Gist options
  • Save SmallBlackCat/3c3ae08ac73a72f42443 to your computer and use it in GitHub Desktop.
Save SmallBlackCat/3c3ae08ac73a72f42443 to your computer and use it in GitHub Desktop.
//
// NSObject+Association.h
//
// Created by Maciej Swic on 03/12/13.
// Released under the MIT license.
//
#import <Foundation/Foundation.h>
@interface NSObject (Association)
- (id)associatedObjectForKey:(NSString*)key;
- (void)setAssociatedObject:(id)object forKey:(NSString*)key;
@end
//
// NSObject+Association.m
//
// Created by Maciej Swic on 03/12/13.
// Released under the MIT license.
//
#import <objc/runtime.h>
#import "NSObject+Association.h"
@implementation NSObject (Association)
static char associatedObjectsKey;
- (id)associatedObjectForKey:(NSString*)key {
NSMutableDictionary *dict = objc_getAssociatedObject(self, &associatedObjectsKey);
return [dict objectForKey:key];
}
- (void)setAssociatedObject:(id)object forKey:(NSString*)key {
NSMutableDictionary *dict = objc_getAssociatedObject(self, &associatedObjectsKey);
if (!dict) {
dict = [[NSMutableDictionary alloc] init];
objc_setAssociatedObject(self, &associatedObjectsKey, dict, OBJC_ASSOCIATION_RETAIN);
} [dict setObject:object forKey:key];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment