前言
最近看了一些runtime的知识点,虽然我是做的项目开发不是sdk,但是我认为我们还是要去了解它,学习它,这是oc的基本。
代码
//获取本类的类名
NSLog(@"这个类的大名为 %s",class_getName([ViewController class]));
//判断这个类是不是元类
NSLog(@"快说你是不是元类===%@",class_isMetaClass([ViewController class]) ? @"是" : @"不是");
//这个类的大小
NSLog(@"告诉我的你的体重 === %zu",class_getInstanceSize([ViewController class]));
//判断一个类是否含有某个方法
NSLog(@"你是否拥有我写的这个方法===%@",class_respondsToSelector([ViewController class],@selector(init)) ? @"拥有" : @"不拥有");
//返回方法名
NSLog(@"我输入的方法的名字为 === %s",sel_getName(@selector(init)));
//判断两个方法是否一样
NSLog(@"我写的两个方法是否一样===%@",sel_isEqual(@selector(init),@selector(load)) ? @"一样" : @"不一样");
/*************有需要的自己去查api,不可能全部列出,我的水平没到*************/
这里列举了runtime的一些基本的方法,获取类的属性,方法之类的。
/**
* 显示所有运用的方法
*/
- (void)loadAllRoad{
unsigned int count = ;
Method *methodList = class_copyMethodList([ViewController class], &count);
for (NSInteger i = ; i < count; i++) {
NSString *name = NSStringFromSelector(method_getName(methodList[i]));
NSLog(@"本类的运行的所有方法 ==%@",name);
}
}
/**
* 显示所有的本类的属性
*/
- (void)loadAllProperty{
unsigned int count = ;
Ivar *ivarList = class_copyIvarList([ViewController class], &count);
for (NSInteger i = ; i < count; i++) {
NSString *name = @(ivar_getName(ivarList[i]));
NSLog(@"本类的属性有== %@",name);
}
}
找出类的所有的属性和方法,遍历整个类.
/**
* 用于交换的方法
*/
- (void)changeViewDidAppear{
NSLog(@"<%i %s>输出的是我,嘎嘎",__LINE__,__func__);
}
- (void)changeViewDidAppear2{
NSLog(@"<%i %s>第二种交换的输出",__LINE__,__func__);
}
/**
* 第一种黑魔法使用
*/
- (void)swizzOne{
//获取方法
Method oldMeth = class_getInstanceMethod([ViewController class],@selector(viewDidAppear:));
Method newMeth = class_getInstanceMethod([ViewController class], @selector(changeViewDidAppear));
method_exchangeImplementations(oldMeth, newMeth);
}
/**
* 第二种黑魔法
*/
- (void)swizzTwo{
//获取方法
Method oldMeth = class_getInstanceMethod([ViewController class],@selector(viewDidAppear:));
Method newMeth = class_getInstanceMethod([ViewController class], @selector(changeViewDidAppear2));
IMP old = method_getImplementation(oldMeth);
IMP new = method_getImplementation(newMeth);
method_setImplementation(oldMeth, new);
method_setImplementation(newMeth, old);
}
这块感觉是runtime用的最多的地方,交换方法实现.
这是我的一些理解,不对之处请指出。
github地址