Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple Objective-C wrapper that allows easier use of Associated Objects.
//
// NSObject+AssociatedValues.h
//
// Created by Shilo White on 11/8/11.
// Copyright (c) 2011 Shilocity Productions. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface NSObject (AssociatedValues)
- (void)setAssociatedValue:(id)value forKey:(NSString *)key;
- (void)setAssociatedValue:(id)value forKey:(NSString *)key policy:(objc_AssociationPolicy)policy;
- (id)associatedValueForKey:(NSString *)key;
- (void)removeAssociatedValueForKey:(NSString *)key;
- (void)removeAllAssociatedValues;
@end
@implementation NSObject (AssociatedValues)
- (void)setAssociatedValue:(id)value forKey:(NSString *)key {
[self setAssociatedValue:value forKey:key policy:OBJC_ASSOCIATION_ASSIGN];
}
- (void)setAssociatedValue:(id)value forKey:(NSString *)key policy:(objc_AssociationPolicy)policy {
objc_setAssociatedObject(self, key, value, policy);
}
- (id)associatedValueForKey:(NSString *)key {
return objc_getAssociatedObject(self, key);
}
- (void)removeAssociatedValueForKey:(NSString *)key {
objc_setAssociatedObject(self, key, nil, OBJC_ASSOCIATION_ASSIGN);
}
- (void)removeAllAssociatedValues {
objc_removeAssociatedObjects(self);
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.