一直对iOS的runtimer机制不太理解,或者是理解有偏差,趁着最近不忙,认真的研究了一下,
runtimer 简称运行时,就是系统在运行时候的一些机制,其中最主要的是消息机制,对于c语言,函数的调用在编译的时候会决定调用哪个函数,编译完成之后直接按顺序执行,OC的函数调用属于动态调用,在编译的时候并不能决定真正调用哪个函数,只有在真正的运行时才会根据函数的名字找到对应的函数去调用
obj-c 是基于c语言加入了面向对象特性和消息转发机制的一门动态语言,他不仅需要编译器来编译,还需要runtimer系统来动态的创建类和对象,
那么runTimer可以帮助我们做哪些事情呢,其实目前我使用的地方也不是太多,主要用来做按钮事件的绑定,还有就是替换系统的方法。
run timer 的的简单使用
1.拦截方法
2.交换方法
3.分类中添加添加属性
4.字典转model
一、拦截交换方法
#import "NSArray+Extension.h"
#import <objc/runtime.h>
@implementation NSArray (Extension)
+ (void)load{
[super load];
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{ //方法交换只要一次就好
Method oldObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(objectAtIndex:));
Method newObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(自己定义的方法:));
method_exchangeImplementations(oldObjectAtIndex, newObjectAtIndex);
});
}
二、动态的增加一个属性
#import <UIKit/UIKit.h>
@interface UIControl (Extension)
@property (nonatomic, strong) NSString *tagss;
@end
#import "UIControl+Extension.h"
#import "objc/runtime.h"
static const void * tagsBy = &tagsBy;
@implementation UIControl (Extension)
@dynamic tagss;
- (void)setTagss:(NSString *)tagss{
objc_setAssociatedObject(self, tagsBy, tagss, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
-(NSString *)tagss {
return objc_getAssociatedObject(self, tagsBy);
}
@end
网友评论