不会调用NSMutableDictionary的Swizzled方法

时间:2016-05-28 05:42:00

标签: ios objective-c nsmutabledictionary swizzling method-swizzling

我试图调动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

3 个答案:

答案 0 :(得分:6)

NSMutableDictionaryclass cluster。它是许多实现实际工作的Apple私有具体子类的抽象基类。作为子类,它们会覆盖-setObject:forKey:NSMutableDictionary本身没有真正实现该方法,也没有尝试调用它。因此,没有任何东西可以替代您的替代实施。

答案 1 :(得分:0)

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

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

答案 2 :(得分: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