API - 类
- 动态创建一个类(参数:父类,类名,额外的内存空间)
- Class objc_allocateClassPair(Class superclass, const char *name, size_t extraBytes)
- 注册一个类(要在类注册之前添加成员变量)
- void objc_registerClassPair(Class cls)
#import <objc/runtime.h>
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//创建类
Class newClass = objc_allocateClassPair([NSObject class],"Dog",0);
//第4个参数表示为对齐,3个为几个字节
//添加成员变量
class_addIvar(newClass,"_age",4,1,@encode(int));
class_addIvar(newClass,"_weight",4,1,@encode(int));
class_addMethod(newClass,@selector(run),(IMP)run,"v@:");
//注册类,一旦类注册完毕类的结构已经决定,不能再添加变量
objc_registerClassPair(newClass);
id dog = [[newClass alloc]init];
[dog setValue:@(10) forKey:@"_age"];
[dog setValue:@(20) forKey:@"_weight"];
[dog run];
NSLog(@"age = %@, weight = %@",[dog valueForKey:@"_age"],[dog valueForKey:@"_weight"]);
//在不需要这个类的时候释放
objc_disposeClassPair(newClass);
return YES;
}
- 销毁一个类
- void objc_disposeClassPair(Class cls)
- 获取isa指向的Class
- Class object_getClass(id obj)
- 设置isa指向的Class
- Class object_setClass(id obj, Class cls)
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
Person *person = [[Person alloc]init];
[person run];
object_setClass(person,[Car class]);
[person run];
return YES;
}
上面的代码经过 object_setClass
后 person
变为 Car
类型的,控制台的输出如下:
2022-06-05 16:27:36.180629+0800 TestPod[41697:189747] -[Person run]
2022-06-05 16:30:03.061300+0800 TestPod[41697:189747] -[Car run]
其isa指针变化如下图所示:
- 判断一个OC对象是否为Class
- BOOL object_isClass(id obj)
NSLog(@"%d %d %d",object_isClass(person),object_isClass([Person class]), object_isClass(object_getClass([Person class])));
上面除了 person
不是 Class
外,其他两个都是 Class
- 判断一个Class是否为元类
- B00L class_isMetaClass(Class cls)
- 获取父类
- Class class_getSuperclass(Class cls)
API - 成员变量
- 获取一个实例变量
Ivar class_getInstanceVariable(Class cls, const char *name)
用法如下:
//获取成员变量信息
Ivar ageVar = class_getInstanceVariable([Person class], "_age");
NSLog(@"%s %s",ivar_getName(ageVar),ivar_getTypeEncoding(ageVar));
输出结果:
2022-06-07 19:57:59.023243+0800 TestPod[14761:1648955] _age i
- 拷贝实例变量列表(最后需要调用free释放)
Ivar *class_copyIvarlist(Class cls, unsigned int *outCount)
//成员变量的数值
unsigned int count;
Ivar *ivars = class_copyIvarList([Person class], &count);
for (int i = 0; i < count; i++)
{
//取出i位置的成员变量
Ivar ivar = ivars[i];
NSLog(@"%s %s",ivar_getName(ivar),ivar_getTypeEncoding(ivar));
}
//runtime中调用copy或者create创建出来的都需要释放
free(ivars);
输出结果为:
2022-06-09 10:30:55.223196+0800 TestPod[2000:400561] _age i
2022-06-09 10:30:55.223232+0800 TestPod[2000:400561] _name @"NSString"
通过上面的办法,我们可以输出系统类的成员属性,并通过其他方式来修改它,例如下面这个是通过 KVC
的方式来修改 TextField
的 placeHolder
的文字颜色
//成员变量的数值
unsigned int count;
Ivar *ivars = class_copyIvarList([UITextField class], &count);
for (int i = 0; i < count; i++)
{
//取出i位置的成员变量
Ivar ivar = ivars[i];
NSLog(@"---%s %s",ivar_getName(ivar),ivar_getTypeEncoding(ivar));
}
//runtime中调用copy或者create创建出来的都需要释放
free(ivars);
UITextField *textField = [[UITextField alloc]init];
textField.placeholder = @"11111";
//下面这个是拿到打印出来的placeholder相关的一个属性
UILabel *placeHolderLabel = [textField valueForKey:@"_placeHolderLabel"];
placeHolderLabel.textColor = [UIColor redColor];
//或者用下面的办法
[textField setValue:[UIColor redColor] forKey:@"_placeHolderLabel.textColor"];
还可以通过给 'NSObject' 添加类别的方式来解析属性值,如下所示:
#import <objc/runtime.h>>
#import "NSObject+Json.h"
@implementation NSObject (Json)
+ (instancetype)My_objectWithJson:(NSDictionary *)dict
{
id obj = [[self alloc]init];
unsigned int count;
Ivar *ivars = class_copyIvarList(self, &count);
for (int i = 0; i < count; i++)
{
Ivar ivar = ivars[i];
NSString *name = [NSString stringWithUTF8String:ivar_getName(ivar)];
NSMutableString *str = [NSMutableString stringWithString:name];
[str deleteCharactersInRange:NSMakeRange(0, 1)];
//设值
[obj setValue:dict[str] forKey:name];
}
return obj;;
}
然后解析属性值,这样即可:
Person *per = [Person My_objectWithJson:dict];
- 设置和获取成员变量的值
void object_setIvar(id obj, Ivar ivar, id value)
object_getIvar(id obj, Ivar ivar)
//设置和获取成员变量的值
Ivar nameIvar = class_getInstanceVariable([Person class],"_name");
Person *p = [[Person alloc]init];
object_setIvar(p, nameIvar, @"123");
object_getIvar(p, nameIvar);
object-setIvar(p, ageIvar, (_bridge id)(void *)10);
NSLog(@"%@",p.name);
//输出结果
2022-06-07 20:13:33.309974+0800 TestPod[15127:1666081] 123
- 动态添加成员变量(已经注册的类是不能动态添加成员变量的)
B00L class_addIvar(Class cls, const char * hane, size_t size, uint8_t alignnent, const char * types) - 获取成员变量的相关信息
const char *ivar_getName(Ivar v)
const char *ivar_getTypeEncoding(Ivar v)
方法的API
获得一个实例方法、类方法
- Method class_getInstanceMethod(Class cls, SEL nane)
- Method class_getClassMethod(Class cls, SEL nane)
方法实现相关操作
- IMP class_getMethodImplementation(Class cls, SEL name)
- IMP method_setImplenentation(Method n, IMP imp)
- void method_exchangeImplenentations(Method ml, Method m2)
#import "Person.h"
@implementation Person
- (void)run
{
NSLog(@"%s",__func__);
}
- (void)test
{
NSLog(@"%s",__func__);
}
@end
#import "Person.h"
#import <objc/runtime.h>>
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person *person = [[Person alloc]init];
Method runMethod = class_getInstanceMethod([Person class], @selector(run));
Method testMethod = class_getInstanceMethod([Person class], @selector(test));
method_exchangeImplementations(runMethod, testMethod);
[person run];
}
return 0;
}
拷贝方法列表(最后需要调用free释放)
- Method *class_copyMethodlist(Class cls, unsigned int woutCount)
·动态添加方法
- B00L class_addMethod(Class cls,SEL nane,IMP inp,const char *types)
动态替换方法
- IMP class_replaceMethod(Class cls, SEL name, IMP imp, const char *types)
#import "Person.h"
#import <objc/runtime.h>>
#import <Foundation/Foundation.h>
void myRun()
{
NSLog(@"myRun");
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person *person = [[Person alloc]init];
class_replaceMethod([Person class], @selector(run), (IMP)myRun, "v");
//或者用下面这种方式
class_replaceMethod([Person class], @selector(run), imp_implementationWithBlock(^{
NSLog(@"123123");
}), "v");
[person run];
}
return 0;
}
获取方法的相关信息(带有copy的需要弱用free去释放)
- SEL method_getName(Method m).
- IMP method_getImplementation(Method m)
- const char *method_getTypeEncoding(Method m)
- unsiqned int method_getNumberOfArguments(Method m)
- char enethod_copyReturnType(Method m)
- char *method_copyArgumentType(Method m, unsigned int index)
Runtime总结
1.什么是Runtime?平时项目中有用过么?
- OC是一门动态性比较强的编程语言,允许很多操作推迟到程序运行时再进行
- OC的动态性就是由Runtime来支撑和实现的,Runtime是一套C语言的API,封装了很多动态性相关的函数
- 平时编写的OC代码,底层都是转换成了Runtime APl进行调用
- 具体应用
- 利用关联对象(AssociatedObject)给分类添加属性
- 遍历类的所有成员变量(修改textfield的占位文字颜色、字典转模型、自动归档解档)
- 交换方法实现(交换系统的方法)
- 利用消息转发机制解决方法找不到的异常问题
例子
如果想要监听系统的方法,或者在系统方法的基础上做一些改变,可以使用下面的方法,这种方式就叫 HOOK
- 例子1
监听按钮的点击事件
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
NSArray *array = [NSArray arrayWithObjects:@"1",nil];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(100, 100, 80, 40);
button.backgroundColor = [UIColor redColor];
[button addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
- (void)buttonClick
{
NSLog(@"%s",__func__);
}
@end
#import <objc/runtime.h>>
#import "UIControl+Extention.h"
@implementation UIControl (Extention)
+ (void)load
{
Method method1 = class_getInstanceMethod(self, @selector(sendAction:to:forEvent:));
Method method2 = class_getInstanceMethod(self, @selector(mySendAction:to:forEvent:));
method_exchangeImplementations(method1, method2);
}
- (void)mySendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event
{
NSLog(@"%@---%@---%@",self,target,NSStringFromSelector(action));
if ([self isKindOfClass:[UIButton class]])
{
[self mySendAction:action to:target forEvent:event];
}
}
@end
- 例子2
防止数组里添加 nil
的对象,这里注意虽然类型是 NSMutableArray
类型的,但其底层却不是这样的,故在交换之前最好通过 [array class]
来打印一下对象的类型
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
NSObject *obj = nil;
NSMutableArray *array = [NSMutableArray array];
[array addObject:@"1"];
[array insertObject:obj atIndex:0];
}
@end
#import <objc/runtime.h>
#import "NSArray+Extension.h"
@implementation NSArray (Extension)
+ (void)load
{
Class class = NSClassFromString(@"__NSArrayM");
Method method1 = class_getInstanceMethod(class, @selector(insertObject:atIndex:));
Method method2 = class_getInstanceMethod(class, @selector(mj_insertObject:atIndex:));
method_exchangeImplementations(method1, method2);
}
- (void)mj_insertObject:(id)object atIndex:(NSUInteger)index
{
if (object == nil) return;;
[self mj_insertObject:object atIndex:index];
}
@end
通过上面两个例子我们可以尝试修改系统字体
网友评论