How can I get a list of classes already loaded into memory in a specific package (or binary)?

You can get a list of classes from a collection through NSBundleDidLoadNotification . But I can’t understand how I can get them from an already downloaded package. (same kit with code)

I am trying to get the class list of my application package. More specifically, classes are only in my binary application.

I looked at objc_getClassList , but it returns ALL classes, and this is clearly too hard for me. I need an easy method. I found objc_copyClassNamesForImage by googling but it is not documented and I don't know how to use it safely. I think I can try to use it traditionally, but I want to find another safe option before heading there.

+7
source share
3 answers

Another option would be to iterate over all classes registered at runtime and use +[NSBundle bundleForClass:] for each of them to figure out which one. Then you can sort things in sets based on the result.

Something like that:

 @interface NSBundle (DDAdditions) - (NSArray *)definedClasses_dd; @end @implementation NSBundle (DDAdditions) - (NSArray *)definedClasses_dd { NSMutableArray *array = [NSMutableArray array]; int numberOfClasses = objc_getClassList(NULL, 0); Class *classes = calloc(sizeof(Class), numberOfClasses); numberOfClasses = objc_getClassList(classes, numberOfClasses); for (int i = 0; i < numberOfClasses; ++i) { Class c = classes[i]; if ([NSBundle bundleForClass:c] == self) { [array addObject:c]; } } free(classes); return array; } @end 

Then you can call:

 NSLog(@"%@", [[NSBundle mainBundle] definedClasses_dd]); 
+4
source

Try this magic:

 -(NSArray*)getClassNames{ NSMutableArray* classNames = [NSMutableArray array]; unsigned int count = 0; const char** classes = objc_copyClassNamesForImage([[[NSBundle mainBundle] executablePath] UTF8String], &count); for(unsigned int i=0;i<count;i++){ NSString* className = [NSString stringWithUTF8String:classes[i]]; [classNames addObject:className]; } return classNames; } 
+4
source

Here I could find an example for the objc_copyClassNamesForImage function.

http://www.opensource.apple.com/source/objc4/objc4-493.9/test/weak.m

 // class name list const char *image = class_getImageName(objc_getClass("NotMissingRoot")); testassert(image); const char **names = objc_copyClassNamesForImage(image, NULL); testassert(names); testassert(classInNameList(names, "NotMissingRoot")); testassert(classInNameList(names, "NotMissingSuper")); if (weakMissing) { testassert(! classInNameList(names, "MissingRoot")); testassert(! classInNameList(names, "MissingSuper")); } else { testassert(classInNameList(names, "MissingRoot")); testassert(classInNameList(names, "MissingSuper")); } free(names); 

The source code is unofficial, but from Apple. So I decided to use this code until I find a better way.

+1
source

All Articles