Skip to content

Instantly share code, notes, and snippets.

@Shilo
Created November 9, 2011 05:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Shilo/1350553 to your computer and use it in GitHub Desktop.
Save Shilo/1350553 to your computer and use it in GitHub Desktop.
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