oc@swift hook

2021-01-01 00:00:00

cxdt

oc 

///////////////////////////

#import#import "Hook.h"

@implementation Hook

+ (void)sMethod:(SEL)ag1 sClass:(Class)class wMethod:(SEL)ag2 {

    Method oMethod = class_getInstanceMethod(class, ag1);

    Method nMethod = class_getInstanceMethod(class, ag2);

    method_exchangeImplementations(oMethod, nMethod);

}

@end

#import "ViewController.h"

#import "Hook.h"

@interface ViewController ()

@end

@implementation ViewController

+ (void)load{

    [Hook sMethod:@selector(click:) sClass:[self class] wMethod:@selector(hookClick:)];

}

- (void)hookClick:(id)sender {

    NSLog(@"hook hahhaha");

    [self hookClick:sender];

}

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

}

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

- (IBAction)click:(id)sender {

    NSLog(@"hahahha");

}

@end

swift ////////////////////////////////////////// 类似

class Hook: NSObject {

    class func sMethod(ag1: Selector,sClass: AnyClass, ag2: Selector) {

        let oMethod = class_getInstanceMethod(sClass, ag1)

        let nMethod = class_getInstanceMethod(sClass, ag2)

        method_exchangeImplementations(oMethod, nMethod)

    }

}

import UIKit

class ViewController: UIViewController {

    override func loadView() {

        super.loadView()

        Hook.sMethod(ag1: #selector(click(_:)),sClass: ViewController.self , ag2: #selector(hookClick(_:)))

    }

    @objc func hookClick(_ sender: UIButton) {

        print("hook HAHA")

        click(sender)

    }

    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

    }

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

    @IBAction func click(_ sender: UIButton) {

        print("hahaha")

        print("-------------")

    }

}

你可能感兴趣的:(oc@swift hook)