ios - 使用运行时替换字典的对象方法无效

标签 ios dictionary runtime

我试图替换字典的setObject:<#(nonnull id)#> forKey:<#(nonnull id<NSCopying>)#>方法与运行时,但失败了。

代码:

#import "NSMutableDictionary+MD5MutableDictionary.h"
#import <objc/runtime.h>

@implementation NSMutableDictionary (MD5MutableDictionary)
+(void)load
{
    Method A = class_getInstanceMethod(self, @selector(setObject:forKey:));

    Method B = class_getInstanceMethod(self ,@selector(testsetObject:forKey:));

    method_exchangeImplementations(A, B);

}

- (void)testsetObject:(id)anObject forKey:(id<NSCopying>)aKey{
    [self testsetObject:anObject forKey:aKey];
    NSLog(@"success");
}

通过变量字典对象直接在外部调用,例如:

NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[dic setObject:@"jack" forKey:@"name"];

最佳答案

如果你真的想实现你的目标,只需尝试下面的代码并处理私有(private)类__NSDictionaryM,它应该可以工作。

@implementation NSMutableDictionary (MD5MutableDictionary)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *className = @"__NSDictionaryM";
        Class class = NSClassFromString(className);

        SEL originalSelector = @selector(setObject:forKey:);
        SEL swizzledSelector = @selector(testsetObject:forKey:);

        Method originalMethod = class_getInstanceMethod(class, originalSelector);
        Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);

        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)testsetObject:(id)anObject forKey:(id<NSCopying>)aKey{
    [self testsetObject:anObject forKey:aKey];
    NSLog(@"success");
}
@end

关于ios - 使用运行时替换字典的对象方法无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57488952/

相关文章:

python - 检查字典是否是另一个字典的子集的递归函数

delphi - 是否可以在运行时有条件地使用 XPManifest?

java - 当前线程不是所有者异常

c - 内循环的运行时间是多少?

iphone - UIActivityViewController - 检测发送错误与取消错误

ios - iOS无需用户交互即可拍摄多张照片

dictionary - 没有为方案WASB获取文件系统。 Hdinsight Mapreduce

ios - 如何从其中的 View Controller 访问选项卡 View Controller ?

ios - 为导航栏和 View 设置相同的颜色,但在运行时获得不同的颜色

java - 在 Struts2 中访问多键映射