面试题引发的思考:
Q: 什么是Runtime?平时项目中有用过么?
- OC是一门动态性比较强的编程语言,允许很多操作推迟到程序运行时再进行;
- OC的动态性就是由Runtime来支撑和实现的,Runtime是一套C语言的API,封装了很多动态性相关的函数;
- 平时编写的OC代码,底层都是转换成了Runtime API进行调用。
Q: 项目中具体应用?
- 利用关联对象(
AssociatedObject
)给分类添加属性; - 遍历类的所有成员变量(修改
textfield
的占位文字颜色、字典转模型、自动归档解档); - 交换方法实现(交换系统的方法);
- 利用消息转发机制解决方法找不到的异常问题;
- ......
1. Runtime API
(1) Runtime API - 类
1.1 动态创建一个类(参数:父类,类名,额外的内存空间)
Class objc_allocateClassPair(Class superclass, const char *name, size_t extraBytes)
1.2 注册一个类(要在类注册之前添加成员变量)
void objc_registerClassPair(Class cls)
1.3 销毁一个类
void objc_disposeClassPair(Class cls)
1.4 获取isa指向的Class
Class object_getClass(id obj)
1.5 设置isa指向的Class
Class object_setClass(id obj, Class cls)
1.6 判断一个OC对象是否为Class
BOOL object_isClass(id obj)
1.7 判断一个Class是否为元类
BOOL class_isMetaClass(Class cls)
1.8 获取父类
Class class_getSuperclass(Class cls)
(2) Runtime API – 成员变量
2.1 获取一个实例变量信息
Ivar class_getInstanceVariable(Class cls, const char *name)
2.2 拷贝实例变量列表(最后需要调用free释放)
Ivar *class_copyIvarList(Class cls, unsigned int *outCount)
2.3 设置和获取成员变量的值
void object_setIvar(id obj, Ivar ivar, id value)
id object_getIvar(id obj, Ivar ivar)
2.4 动态添加成员变量(已经注册的类是不能动态添加成员变量的)
BOOL class_addIvar(Class cls, const char * name, size_t size, uint8_t alignment, const char * types)
2.5 获取成员变量的相关信息
const char *ivar_getName(Ivar v)
const char *ivar_getTypeEncoding(Ivar v)
(3) Runtime API – 属性
3.1 获取一个属性
objc_property_t class_getProperty(Class cls, const char *name)
3.2 拷贝属性列表(最后需要调用free释放)
objc_property_t *class_copyPropertyList(Class cls, unsigned int *outCount)
3.3 动态添加属性
BOOL class_addProperty(Class cls, const char *name, const objc_property_attribute_t *attributes, unsigned int attributeCount)
3.4 动态替换属性
void class_replaceProperty(Class cls, const char *name, const objc_property_attribute_t *attributes, unsigned int attributeCount)
3.5 获取属性的一些信息
const char *property_getName(objc_property_t property)
const char *property_getAttributes(objc_property_t property)
(4) Runtime API – 方法
4.1 获得一个实例方法、类方法
Method class_getInstanceMethod(Class cls, SEL name)
Method class_getClassMethod(Class cls, SEL name)
4.2 方法实现相关操作
IMP class_getMethodImplementation(Class cls, SEL name)
IMP method_setImplementation(Method m, IMP imp)
void method_exchangeImplementations(Method m1, Method m2)
4.3 拷贝方法列表(最后需要调用free释放)
Method *class_copyMethodList(Class cls, unsigned int *outCount)
4.4 动态添加方法
BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types)
4.5 动态替换方法
IMP class_replaceMethod(Class cls, SEL name, IMP imp, const char *types)
4.6 获取方法的相关信息(带有copy的需要调用free去释放)
SEL method_getName(Method m)
IMP method_getImplementation(Method m)
const char *method_getTypeEncoding(Method m)
unsigned int method_getNumberOfArguments(Method m)
char *method_copyReturnType(Method m)
char *method_copyArgumentType(Method m, unsigned int index)
4.7 选择器相关
const char *sel_getName(SEL sel)
SEL sel_registerName(const char *str)
4.8 用block作为方法实现
IMP imp_implementationWithBlock(id block)
id imp_getBlock(IMP anImp)
BOOL imp_removeBlock(IMP anImp)
2. Runtime 应用
(1) 利用关联对象(AssociatedObject
)给分类添加属性
// TODO: ----------------- Person类 -----------------
@interface Person : NSObject
@property (nonatomic, assign) int age;
@end
@implementation Person
@end
// TODO: ----------------- Person (Category1)类 -----------------
@interface Person (Category)
@property (nonatomic, copy) NSString *name;
@end
@implementation Person (Category)
- (void)setName:(NSString *)name {
objc_setAssociatedObject(self, @selector(name), name, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (NSString *)name {
return objc_getAssociatedObject(self, _cmd);
}
@end
// TODO: ----------------- ViewController类 -----------------
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
Person *person = [[Person alloc] init];
person.age = 10;
person.name = @"Tom";
NSLog(@"age - %d, weight - %@", person.age, person.name);
}
// 打印结果
Demo[1234:567890] age - 10, weight - Tom
(2) 遍历类的所有成员变量
修改textfield
的占位文字颜色
// 方法一
self.textField.attributedPlaceholder = [[NSMutableAttributedString alloc] initWithString:@"请输入用户名"
attributes:@{NSForegroundColorAttributeName : [UIColor redColor]}];
// 方法二
self.textField.placeholder = @"请输入用户名";
[self.textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
字典转模型
// TODO: ----------------- Person类 -----------------
@interface Person : NSObject
@property (nonatomic, assign) int weight;
@property (nonatomic, assign) int age;
@property (nonatomic, copy) NSString *name;
@end
@implementation Person
@end
// TODO: ----------------- NSObject (Json)类类 -----------------
@interface NSObject (Json)
+ (instancetype)my_objectWithJson:(NSDictionary *)dict;
@end
@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];
NSMutableString *name = [NSMutableString stringWithUTF8String:ivar_getName(ivar)];
[name deleteCharactersInRange:NSMakeRange(0, 1)];
[obj setValue:dict[name] forKey:name];
}
free(ivars);
return obj;
}
@end
// TODO: ----------------- Person类 -----------------
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
NSDictionary *dict = @{@"age": @20, @"weight": @60, @"name": @"jack"};
Person *person = [Person my_objectWithJson:dict];
NSLog(@"age - %d weight - %d name - %@", person.age, person.weight, person.name);
}
return 0;
}
// 打印结果
Demo[1234:567890] age - 20 weight - 60 name - jack
(3) 交换方法实现
交换系统的方法
// TODO: ----------------- NSMutableArray (Extension)类 -----------------
@interface NSMutableArray (Extension)
@end
@implementation NSMutableArray (Extension)
+ (void)load {
// 类簇:NSString、NSArray、NSDictionary,真实类型是其他类型
Class cls = NSClassFromString(@"__NSArrayM");
Method method1 = class_getInstanceMethod(cls, @selector(insertObject:atIndex:));
Method method2 = class_getInstanceMethod(cls, @selector(my_insertObject:atIndex:));
method_exchangeImplementations(method1, method2);
}
- (void)my_insertObject:(id)anObject atIndex:(NSUInteger)index {
if (anObject == nil) {
return;
}
[self my_insertObject:anObject atIndex:index];
}
@end
// TODO: ----------------- ViewController类 -----------------
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *obj = nil;
NSMutableArray *array = [NSMutableArray array];
[array addObject:@"jack"];
[array insertObject:obj atIndex:0];
NSLog(@"array - %@", array);
}
// 打印结果
Demo[1234:567890] array - ( jack )
(4) 利用消息转发机制解决方法找不到的异常问题
// TODO: ----------------- Person类 -----------------
@interface Person : NSObject
- (void)run;
- (void)test;
- (void)other;
@end
@implementation Person
- (void)run {
NSLog(@"%s", __func__);
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
// 可以调用的方法
if ([self respondsToSelector:aSelector]) {
return [super methodSignatureForSelector:aSelector];
}
// 无法找到的方法
return [NSMethodSignature signatureWithObjCTypes:"v@:"];
}
- (void)forwardInvocation:(NSInvocation *)anInvocation {
NSLog(@"找不到%@方法", NSStringFromSelector(anInvocation.selector));
}
@end
// TODO: ----------------- main -----------------
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
Person *person = [[Person alloc] init];
[person run];
[person test];
[person other];
}
return 0;
}
// 打印结果
Demo[1234:567890] -[Person run]
Demo[1234:567890] 找不到test方法
Demo[1234:567890] 找不到other方法