iosobjective-cnsobjectdladdr

Get List of all native classes


I want to get all the native classes (NSString, NSNumber, int, float, NSSet, NSDictionary) that I have loaded into my iOS Project..

i.e., if I have created a custom class named "TestClass" I don't want it listed...

I have already got a code but it returns names of all classes loaded any way I can modify the code to limit the list to Native classes only?

#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

}

Solution

  • You would get all loaded classes with

    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);
    }
    

    (Code from objc_getClassList documentation.)

    To restrict the list, you can check the bundle from which the class was loaded, e.g.

    Class c = classes[i];
    NSBundle *b = [NSBundle bundleForClass:c];
    if (b != [NSBundle mainBundle])
        ...
    

    for all classes that are not loaded from your application.