面向切片编程:钩子方法(hook)

HOOK方法的使用

导入第三方框架:Aspects

    UIView *v = [UIView new];
    [self.view addSubview:v];
    //NSSelectorFromString方法,系统会为其找到字符串所对应的方法

    //AspectPositionBefore( = 2 ):在钩子方法之前调用闭包
    //AspectPositionInstead( = 1 ):闭包替换钩子方法
    //AspectPositionAfter( = 0 ):在钩子方法之后调用闭包
    [v aspect_hookSelector: NSSelectorFromString(@"dealloc") withOptions:AspectPositionBefore usingBlock:^{
        NSLog(@"--view  dealloc--");
    }error:nil];

performSelector方法: 找出一个函数类没有对外显示的方法

    Animal *ani = [Animal new];
    [ani performSelector:@selector(demoFunc)];


    [self performSelector:@selector(xxx)];
    //方法没有实现
    - (void)doesNotRecognizeSelector:(SEL)aSelector {
    NSLog(@"---->%@",NSStringFromSelector(aSelector));
    //若不调用父类方法,则不会打印错误信息
    [super doesNotRecognizeSelector:aSelector];
}

将类的两个实例的实例函数方法进行交换

#import "Cat.h"
#import <objc/objc-runtime.h>

@implementation Cat
- (void)printA{

    NSLog(@"A");
}

- (void)printB{

    NSLog(@"B");
}

- (void)demoFunc{

    
    Method method_A =  class_getInstanceMethod([self class], @selector(printA));
    
    Method method_B = class_getInstanceMethod([self class], @selector(printB));
    
    method_exchangeImplementations(method_A, method_B);
}
@end

没有调用交换方法时,打印输出: A B
调用方法之后,打印输出: B A

    Cat *cat = [Cat new];
    //调用函数,交换打印输出
    [cat demoFunc];
    [cat printA];
    [cat printB];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 前言 如何把这个世界变得美好?把你自己变得更美好 我们这篇博客继续来介绍Runtime在开发中的实际应用,通过开源...
    Dely阅读 6,478评论 4 16
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,337评论 19 139
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 11,713评论 0 17
  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 5,820评论 0 9
  • importUIKit classViewController:UITabBarController{ enumD...
    明哥_Young阅读 9,427评论 1 10