我正在尝试调配 NSMutableDictionary。我在这里做错了什么?我正在尝试为 NSMutableDictionary 覆盖 setObject:forKey:。
#import "NSMutableDictionary+NilHandled.h"
#import <objc/runtime.h>
@implementation NSMutableDictionary (NilHandled)
+ (void)load{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];
SEL originalSelector = @selector(setObject:forKey:);
SEL swizzledSelector = @selector(swizzledSetObject:forKey:);
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
class_replaceMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
BOOL didAddMethod = class_addMethod(class,originalSelector,method_getImplementation(swizzledMethod),method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(class,swizzledSelector,method_getImplementation(originalMethod),method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
});
}
- (void) swizzledSetObject:(id)anObject forKey:(id<NSCopying>)aKey
{
[self swizzledSetObject:anObject?anObject:@"Nil" forKey:aKey];
}
@结尾