面试题答案
一键面试获取属性列表
#import <objc/runtime.h>
// 获取类的属性列表
NSMutableArray *getProperties(Class class) {
NSMutableArray *properties = [NSMutableArray array];
unsigned int outCount, i;
objc_property_t *propertiesList = class_copyPropertyList(class, &outCount);
for (i = 0; i < outCount; i++) {
objc_property_t property = propertiesList[i];
const char *propertyName = property_getName(property);
[properties addObject:[NSString stringWithUTF8String:propertyName]];
}
free(propertiesList);
return properties;
}
使用场景:
- 序列化和反序列化:当需要将对象转换为JSON或者从JSON恢复对象时,通过获取属性列表可以知道对象有哪些属性,方便进行数据的转换。
- 数据绑定:在一些视图和数据模型绑定的场景中,知道对象的属性列表有助于自动将模型数据显示到对应的视图控件上。
获取方法列表
#import <objc/runtime.h>
// 获取类的方法列表
NSMutableArray *getMethods(Class class) {
NSMutableArray *methods = [NSMutableArray array];
unsigned int outCount, i;
Method *methodList = class_copyMethodList(class, &outCount);
for (i = 0; i < outCount; i++) {
Method method = methodList[i];
SEL methodSEL = method_getName(method);
NSString *methodName = NSStringFromSelector(methodSEL);
[methods addObject:methodName];
}
free(methodList);
return methods;
}
使用场景:
- 方法调度:在实现一些通用的调用框架时,通过获取方法列表,可以动态决定调用哪个方法,实现灵活的调度机制。
- 日志记录:在需要记录对象所有被调用的方法时,通过获取方法列表,结合方法调用的监控机制,可以记录下对象运行过程中调用的所有方法。