序言
有时候我们需要获取整个工程特定类的集合.比如获取所有控制器名称,然后做埋点,归因,追踪等等,尤其是在大数据的时代,获取用户的关注,感兴趣的地方,从而精推用户喜欢的东西,只有这样才能留住用户,延长 APP 的在线使用时间,从而创造更多的价值.
直接上代码
#import <dlfcn.h>
#import <objc/runtime.h>
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self getAllClassName];
}
- (void)getAllClassName {
unsigned int count;
const char **classes;
Dl_info info;
void *_mh_execute_header = __builtin_return_address(0);
//1.获取app的路径
dladdr(_mh_execute_header, &info);
//2.返回当前运行的app的所有类的名字,并传出个数
//classes:二维数组 存放所有类的列表名称
//count:所有的类的个数
classes = objc_copyClassNamesForImage(info.dli_fname, &count);
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (int i = 0; i < count; i++) {
//3.遍历并打印,转换Objective-C的字符串
NSString *className = [NSString stringWithCString:classes[i] encoding:NSUTF8StringEncoding];
if ([className containsString:@"ViewController"]) {
NSLog(@"class name =========== %@", className);
[dict setObject:@" " forKey:className];
}
//根据类名调用
}
NSString * p = @"/Users/Desktop";
NSString *ps = [p stringByAppendingPathComponent:@"news.plist"];
[dict writeToFile:ps atomically:YES];
}
运行结果
总结
技术源于分享,生活源于创造.