有时在代码中会有需要调用私有方法的场景,如不想import太多头文件;想组件设计一些解耦的模块;查看别人模块中未暴露的代码进行分析等。
在 ios 中调用私有方法有很多种方式,主要是通过Runtime去实现。下面自己也测试一下。
新建一个Person类,Person.h中不写代码,Person.m中如下:
#import "Person.h" @implementation Person - (void)eat { NSLog(@"xxx eat===="); } - (void)eat:(NSString *)str str2:(NSString *)str2 str3:(NSString *)str3 { NSLog(@"xxx eat====%@==%@==%@", str, str2, str3); } @end
【找到该类methodLists里的方法】
要想调用私有方法,首先要知道类有什么哪些方法。可以通过如下代码得到方法的一些信息:(不管私有还是公有,只要在该类的methodLists里)
// 获取实例方法 - (void)getMethods { int outCount = 0; Person *p = [Person new]; Method *methods = class_copyMethodList([p class], &outCount); for (int i = 0; i < outCount; i ++) { NSLog(@"=============%d", i); // 获取方法名 Method method = methods[i]; SEL methodName = method_getName(method); NSLog(@"方法名= %@", NSStringFromSelector(methodName)); // 获取参数 char argInfo[512] = {}; unsigned int argCount = method_getNumberOfArguments(method); for (int j = 0; j < argCount; j ++) { // 参数类型 method_getArgumentType(method, j, argInfo, 512); NSLog(@"参数类型= %s", argInfo); memset(argInfo, '