0

我正在尝试调配 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];
}

@结尾

4

3 回答 3

7

NSMutableDictionary是一个类簇。它是许多实现实际工作的 Apple 私有具体子类的抽象基类。作为子类,它们覆盖-setObject:forKey:. 该方法NSMutableDictionary本身没有真正的实现,也没有任何尝试调用它。因此,没有什么可以调用您的替换实现。

于 2016-05-28T08:01:07.443 回答
0

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

可能更有用的是一个方法,如果它是 nil,它不会尝试添加,甚至删除对象。这样,objectForKey 将返回 nil,与您传入的相同。

于 2016-05-28T12:17:51.140 回答
0

更改代码:

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

于 2020-03-17T08:35:16.050 回答