사남봉자늙은 당나귀

2323 단어
부지런하면 졸렬한 것을 보충할 수 있고 코드를 많이 두드릴 수 있다
// * Returns a specified instance method for a given class.
   :Method class_getInstanceMethod(Class cls, SEL name)

// * Returns the implementation of a method.
   :IMP method_getImplementation(Method m)

// * Returns a string describing a method's parameter and return types.
   :const char method_getTypeEncoding(Method m)

// * Adds a new method to a class with a given name and implementation.
   :BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types)

// * Replaces the implementation of a method for a given class.
   :IMP class_replaceMethod(Class cls, SEL name, IMP imp, const char *types) 

// * Exchanges the implementations of two methods.
   :void method_exchangeImplementations(Method m1, Method m2)


#import "Test.h"
#import 

void SwizzleMethod(Class clazz, SEL origin, SEL current) {
    Method originMethod = class_getInstanceMethod(clazz, origin);
    Method currentMethod = class_getInstanceMethod(clazz, current);
    
    IMP originIMP = method_getImplementation(originMethod);
    IMP currentIMP = method_getImplementation(currentMethod);
    
    const char * originType = method_getTypeEncoding(originMethod);
    const char * currentType = method_getTypeEncoding(currentMethod);
    
    BOOL success = class_addMethod(clazz, origin, currentIMP, currentType);
    if (success) {
        class_replaceMethod(clazz, current, originIMP, originType);
    } else {
        method_exchangeImplementations(originMethod, currentMethod);
    }
}

@implementation Test
+ (void)load {
    SwizzleMethod([self class], @selector(method1), @selector(method2));
    SwizzleMethod([self class], @selector(method1), @selector(method3));
}

- (void)method1 {
    NSLog(@"a");
}

- (void)method2 {
    NSLog(@"b");
    [self method2];
}

- (void)method3 {
    NSLog(@"c");
    [self method3];
}

@end

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    Test *text = [[Test alloc] init];
    [text method1];
    
    NSLog(@"---------------------");
    
    [text method2];
    
    NSLog(@"---------------------");
    
    [text method3];
}

좋은 웹페이지 즐겨찾기