未调用 NSMutableDictionary 的 Swizzled 方法 [英] Swizzled method for NSMutableDictionary is not getting called
问题描述
我正在尝试调整 NSMutableDictionary.我在这里做错了什么?我正在尝试为 NSMutableDictionary 覆盖 setObject:forKey:.
I'm trying to swizzle NSMutableDictionary. What am I doing wrong here? I'm trying to override setObject:forKey: for NSMutableDictionary.
#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];
}
@end
推荐答案
NSMutableDictionary
是一个 类簇.它是许多实现实际工作的 Apple 私有的具体子类的抽象基类.作为子类,它们覆盖 -setObject:forKey:
.NSMutableDictionary
本身没有真正实现该方法,也没有尝试调用它.因此,没有什么会调用您的替换实现.
NSMutableDictionary
is a class cluster. It is an abstract base class for a number of Apple-private concrete subclasses that implement the real work. As subclasses, they override -setObject:forKey:
. There is no real implementation of that method on NSMutableDictionary
itself and nothing attempts to call it. Therefore, nothing calls your replacement implementation.
这篇关于未调用 NSMutableDictionary 的 Swizzled 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!