美文网首页
Runtime使用场景

Runtime使用场景

作者: Jean_Lina | 来源:发表于2020-12-07 21:43 被阅读0次
    #import "NSMutableArray+Extension.h"
    #import <objc/runtime.h>
    
    @implementation NSMutableArray (Extension)
    
    + (void)load {
        Class cls = NSClassFromString(@"__NSArrayM");
        Method method1 = class_getInstanceMethod(cls, @selector(insertObject:atIndex:));
        Method method2 = class_getInstanceMethod(cls, @selector(dn_insertObject:atIndex:));
        method_exchangeImplementations(method1, method2);
        
        Method method3 = class_getInstanceMethod(cls, @selector(objectAtIndex:));
        Method method4 = class_getInstanceMethod(cls, @selector(dn_objectAtIndex:));
        method_exchangeImplementations(method3, method4);
    }
    - (void)dn_insertObject:(id)anObject atIndex:(NSUInteger)index {
        if (anObject == nil) {
            return;
        }
        [self dn_insertObject:anObject atIndex:index];
    }
    - (id)dn_objectAtIndex:(NSUInteger)index {
        if (self.count == 0) {
            return nil;
        }
        return [self dn_objectAtIndex:index];
    }
    
    @end
    
    #import "NSMutableDictionary+Extension.h"
    #import <objc/runtime.h>
    
    @implementation NSMutableDictionary (Extension)
    
    + (void)load {
        Class cls = NSClassFromString(@"__NSDictionaryM");
        Method method1 = class_getInstanceMethod(cls, @selector(setObject:forKeyedSubscript:));
        Method method2 = class_getInstanceMethod(cls, @selector(dn_setObject:forKeyedSubscript:));
        method_exchangeImplementations(method1, method2);
        
        Method method3 = class_getInstanceMethod(cls, @selector(setObject:forKey:));
        Method method4 = class_getInstanceMethod(cls, @selector(dn_setObject:forKey:));
        method_exchangeImplementations(method3, method4);
    }
    
    - (void)dn_setObject:(id)obj forKeyedSubscript:(id<NSCopying>)key {
        if (key == nil) {
            return;
        }
        [self dn_setObject:obj forKeyedSubscript:key];
    }
    - (void)dn_setObject:(id)anObject forKey:(id<NSCopying>)aKey {
        if (anObject == nil || aKey == nil) {
            return;
        }
        [self dn_setObject:anObject forKey:aKey];
    }
    
    @end
    

    相关文章

      网友评论

          本文标题:Runtime使用场景

          本文链接:https://www.haomeiwen.com/subject/juhxgktx.html