runtime运行时方法替换的用法

在load方法中,用fc_viewDidLoad替换viewDidLoad:

/**
 *  在load中交换viewDidLoad和fc_viewDidLoad
 */
+(void)load{

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken,^{

        xgf_swizzleSelector([self class], @selector(viewDidLoad), @selector(xgf_viewDidLoad));

        /*Method m1=class_getInstanceMethod([self class], @selector(viewDidLoad));
        Method m2=class_getInstanceMethod([self class], @selector(fc_viewDidLoad));
        BOOL notImplemented=class_addMethod([self class], @selector(viewDidLoad), method_getImplementation(m2), method_getTypeEncoding(m2));
        if(!notImplemented){
        method_exchangeImplementations(m1, m2);
        }
        */
    });
}
static inline void xgf_swizzleSelector(Class class,SEL originalSelector,SEL swizzledSelector){

    Method originalMethod=class_getInstanceMethod(class, originalSelector);
    Method swizzledMethod=class_getInstanceMethod(class, swizzledSelector);
    if(class_addMethod(class, 
                       originalSelector, 
                       method_getImplementation(swizzledMethod),
                       method_getTypeEncoding(swizzledMethod))){
        class_replaceMethod(class, swizzledSelector,
                            method_getImplementation(originalMethod), 
                            method_getTypeEncoding(originalMethod));
    }else{
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}
/**
 *  [self xgf_viewDidLoad] 其实是调用了viewDidLoad的实现
 */
-(void)xgf_viewDidLoad{
    NSLog(@"%s",__func__);
    [self xgf_viewDidLoad];
}