未调用 NSMutableDictionary 的 Swizzled 方法

Swizzled method for NSMutableDictionary is not getting called

我正在尝试调整 NSMutableDictionary。我在这里做错了什么?我正在尝试覆盖 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 是一个 class cluster。它是许多实现实际工作的 Apple 私有具体子 class 的抽象基础 class。作为 subclasses,它们会覆盖 -setObject:forKey:NSMutableDictionary 本身并没有真正实现该方法,也没有人尝试调用它。因此,没有什么会调用您的替换实现。

在被告知为什么它不起作用之后:只需向 NSMutableDictionary 添加一个新方法,如 -(void)setObject:(id)object 或 NullForKey:(NSString*)key。

可能更有用的方法是在对象为 nil 时不尝试添加甚至删除对象。这样,objectForKey 将 return 为零,与您传入的相同。

更改代码:

Class class = [self class];

至:

Class class = NSClassFromString(@"__NSDictionaryM");

对我有用,你可以试试!

这是我的全部代码:

@implementation NSMutableDictionary (Category)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
    [super load];
 Class class = NSClassFromString(@"__NSDictionaryM");
 SEL originalSelector = @selector(setObject:forKey:);
 SEL swizzledSelector = @selector(fu_setObject: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)fu_setObject:(id)anObject forKey:(id<NSCopying>)aKey{
   [self fu_setObject:anObject forKey:aKey];
   
}
@end