Skip to content

Instantly share code, notes, and snippets.

@mralexgray
Last active December 16, 2015 01:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mralexgray/5357310 to your computer and use it in GitHub Desktop.
Save mralexgray/5357310 to your computer and use it in GitHub Desktop.
Nice shortcuts for creating and accessing ObjC Associated Values.
@implementation NSObject (AtoZ_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, (__bridge const void *)(key), value, policy);
}
- (id) associatedValueForKey: (NSString*) key {
return objc_getAssociatedObject(self, (__bridge const void *)(key));
}
- (void) removeAssociatedValueForKey: (NSString*) key {
objc_setAssociatedObject(self, (__bridge const void *)(key), nil, OBJC_ASSOCIATION_ASSIGN);
}
- (void)removeAllAssociatedValues { objc_removeAssociatedObjects(self); }
- (BOOL) hasAssociatedValueForKey:(NSString*)string {
return [self associatedValueForKey:string] != nil;
}
- (id) associatedValueForKey:(NSString*)key orSetTo:(id)anObject policy: (objc_AssociationPolicy) policy {
return [self hasAssociatedValueForKey:key]
? [self associatedValueForKey: key]
: ^{ [self setAssociatedValue:anObject forKey:key policy:policy];
return [self associatedValueForKey:key];
}();
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment