using two runtime: runtime implementation using switched (Method Swizzling)

The actual development process, we may need such a demand: If you want to add some method to determine the conditions for a system or custom methods, but rewriting system method (or custom method) and then modify time and effort where each call, and the result is not better, it is easy to have a situation omissions
so this time we need to use runtime method of exchange, as usual calling systems or custom methods, but the actual run-time to go is the method after we exchanged
now we come look achieve his
call at:

#import "ViewController.h"
#import "NSMutableDictionary+runtime.h"

@interface ViewController ()
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    NSString *key = nil;
    [dic setObject:@"test" forKey:key];
}

In the absence of any treatment, we set a dictionary a key null values ​​will collapse, but here we had a way to exchange, calling setObject: forKey: Before key values ​​do judgment, the following Code switching method


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

@implementation NSMutableDictionary (runtime)

+ (void)load {

    Method method1 = class_getInstanceMethod(objc_getClass("__NSDictionaryM"), @selector(setObject:forKey:));
    Method method2 =  class_getInstanceMethod(objc_getClass("__NSDictionaryM"), @selector(zsh_setObject:forKey:));
    method_exchangeImplementations(method1, method2);
}

- (void)zsh_setObject:(id)anObject forKey:(id<NSCopying>)aKey {
    
    if (aKey != nil) {
        
        [self zsh_setObject:anObject forKey:aKey];
    } else {
        
        NSLog(@"zhousuhua --- akey不可以为空");
    }
}
@end

operation result:

zhousuhua --- akey不可以为空

Here's load method will have to first call ratio main function, as our program is pre-loaded in order to load does not call, where you can put him to delete Here Insert Picture Description
this load will not be executed

Published 40 original articles · won praise 10 · views 30000 +

Guess you like

Origin blog.csdn.net/ai_pple/article/details/90175532