Skip to content

Instantly share code, notes, and snippets.

@yonglam
Created April 10, 2019 12:33
Show Gist options
  • Save yonglam/6ee648dfa137c2f28f56d4597cf9a0af to your computer and use it in GitHub Desktop.
Save yonglam/6ee648dfa137c2f28f56d4597cf9a0af to your computer and use it in GitHub Desktop.
AttachedObject
@interface NSObject (BDWRuntime)
- (void)bdw_attachObject:(id)obj forKey:(NSString *)key;
- (id)bdw_getAttachedObjectForKey:(NSString *)key;
- (void)bdw_attachObject:(id)obj forKey:(NSString *)key isWeak:(BOOL)bWeak;
- (id)bdw_getAttachedObjectForKey:(NSString *)key isWeak:(BOOL)bWeak;
@end
#import "AttachedObject.h"
#import <objc/runtime.h>
@implementation NSObject (BDWRuntime)
- (const void *)bdw_computedKeyFromString:(NSString *)key {
return (char *)((__bridge void*)self) + [key hash] + [key characterAtIndex:0] + [key characterAtIndex:key.length - 1];
}
- (void)bdw_attachObject:(id)obj forKey:(NSString *)key {
[self bdw_attachObject:obj forKey:key isWeak:NO];
}
- (id)bdw_getAttachedObjectForKey:(NSString *)key {
return [self bdw_getAttachedObjectForKey:key isWeak:NO];
}
- (void)bdw_attachObject:(id)obj forKey:(NSString *)key isWeak:(BOOL)bWeak {
if (key.length > 0) {
if (bWeak) {
id __weak weakObject = obj;
id (^block)(void) = ^{ return weakObject; };
objc_setAssociatedObject(self,
[self bdw_computedKeyFromString:key],
block,
OBJC_ASSOCIATION_COPY);
return;
}
else {
objc_setAssociatedObject(self,
[self bdw_computedKeyFromString:key],
obj,
OBJC_ASSOCIATION_RETAIN);
}
}
}
- (id)bdw_getAttachedObjectForKey:(NSString *)key isWeak:(BOOL)bWeak {
if (key.length <= 0) {
return nil;
}
if (bWeak) {
id (^block)(void) = objc_getAssociatedObject(self,
[self bdw_computedKeyFromString:key]);
return (block ? block() : nil);
}
else {
return objc_getAssociatedObject(self,
[self bdw_computedKeyFromString:key]);
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment