我想获得我已加载到iOS项目中的所有本机类(NSString,NSNumber,int,float,NSSet,NSDictionary).
即,如果我创建了一个名为“TestClass”的自定义类,我不希望它列出…
我已经有了一个代码,但它返回了所有类的名称,我可以修改代码将列表限制为仅限于本机类吗?
#import <objc/runtime.h> #import <dlfcn.h> #import <mach-o/ldsyms.h> unsigned int count; const char **classes; Dl_info info; dladdr(&_mh_execute_header,&info); classes = objc_copyClassNamesForImage(info.dli_fname,&count); for (int i = 0; i < count; i++) { NSLog(@"Class name: %s",classes[i]); Class class = NSClassFromString ([NSString stringWithCString:classes[i] encoding:NSUTF8StringEncoding]); // Do something with class }
解决方法
你会得到所有加载的类
int numClasses; Class * classes = NULL; classes = NULL; numClasses = objc_getClassList(NULL,0); if (numClasses > 0 ) { classes = (__unsafe_unretained Class *)malloc(sizeof(Class) * numClasses); numClasses = objc_getClassList(classes,numClasses); for (int i = 0; i < numClasses; i++) { Class c = classes[i]; NSLog(@"%s",class_getName(c)); } free(classes); }
(来自objc_getClassList文档的代码.)
要限制列表,您可以检查从中加载类的包,例如
Class c = classes[i]; NSBundle *b = [NSBundle bundleForClass:c]; if (b != [NSBundle mainBundle]) ...
对于未从您的应用程序加载的所有类.