Last active
December 16, 2015 01:48
-
-
Save mralexgray/5357310 to your computer and use it in GitHub Desktop.
Nice shortcuts for creating and accessing ObjC Associated Values.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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