关键字: runtime 下标语法 字典(NSDictionary)
背景
开发中经常遇到要给某个对象添加的存储的变量,有时候不得不写个熟悉或增加成员变量,如果是系统或第三方类,还需要继承或写分类的方式实现,为了简便开发,利用下标语法和runtime实现给所有对象添加类似字典的存储方式存储值
具体实现
NSObject+ ZQQBindDataLikeDictionary.h
@interface NSObject (ZQQBindDataLikeDictionary)
- (NSObject *)objectForKeyedSubscript:(NSObject *)key;
-(void)setObject:(NSObject *)obj forKeyedSubscript:(NSObject *)key;
@end
NSObject+ ZQQBindDataLikeDictionary.m
import "NSObject+ZQQBindDataLikeDictionary.h"
#import <objc/runtime.h>
#define kZqqExtensionBindDataSaveKey @"kZqqExtensionBindDataSaveKey"
@implementation NSObject (ZQQBindDataLikeDictionary)
- (NSObject *)objectForKeyedSubscript:(NSObject *)key
{
if ([self isKindOfClass:[NSDictionary class]]) {
NSDictionary *dictSelf = (NSDictionary *)self;
return [dictSelf objectForKey:key];
}else{
NSDictionary *bindDict = objc_getAssociatedObject(self,(__bridge const void *)(key));
if (bindDict == nil) {
return nil;
}
return [bindDict objectForKey:kZqqExtensionBindDataSaveKey];
}
return nil;
}
- (void)setObject:(NSObject *)obj forKeyedSubscript:(NSObject *)key
{
if ([self isKindOfClass:[NSMutableDictionary class]]) {
NSDictionary *dictSelf = (NSDictionary *)self;
[dictSelf setObject:obj forKeyedSubscript:key];
}else if ([self isKindOfClass:[NSDictionary class]]) {
// NSDictionary *dictSelf = (NSDictionary *)self;
// [dictSelf setObject:obj forKeyedSubscript:key];
}else{
NSDictionary *bindDict = nil;
if (obj != nil) {
bindDict = @{kZqqExtensionBindDataSaveKey:obj};
}
objc_setAssociatedObject(self, (__bridge const void *)(key), bindDict, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
}
@end