Discover subclasses of a given class in Obj-C

后端 未结 5 1267
北海茫月
北海茫月 2020-12-16 21:15

Is there any way to discover at runtime which subclasses exist of a given class?

Edit: From the answers so far I think I need to clarify a bit more

相关标签:
5条回答
  • 2020-12-16 21:31

    Marc and bbum hit it on the money. This is usually not a good idea.

    However, we have code on our CocoaHeads wiki that does this: http://cocoaheads.byu.edu/wiki/getting-all-subclasses

    0 讨论(0)
  • 2020-12-16 21:40

    There's code in my runtime browser project here that includes a -subclassNamesForClass: method. See the RuntimeReporter.[hm] files.

    0 讨论(0)
  • 2020-12-16 21:44

    Rather than try to automatically register all the subclasses of MYCommand, why not split the problem in two?

    First, provide API for registering a class, something like +[MYCommand registerClass:].

    Then, create code in MYCommand that means any subclasses will automatically register themselves. Something like:

    @implementation MYCommand
    + (void)load
    {
        [MYCommand registerClass:self];
    }
    @end
    
    0 讨论(0)
  • 2020-12-16 21:44

    Not directly, no. You can however get a list of all classes registered with the runtime as well as query those classes for their direct superclass. Keep in mind that this doesn't allow you to find all ancestors for the class up the inheritance tree, just the immediate superclass.

    You can use objc_getClassList() to get the list of Class objects registered with the runtime. Then you can loop over that array and call [NSObject superclass] on those Class objects to get their superclass' Class object. If for some reason your classes do not use NSObject as their root class, you can use class_getSuperclass() instead.

    I should mention as well that you might be thinking about your application's design incorrectly if you feel it is necessary to do this kind of discovery. Most likely there is another, more conventional way to do what you are trying to accomplish that doesn't involve introspecting on the Objective-C runtime.

    0 讨论(0)
  • 2020-12-16 21:53

    Another approach was just published by Matt Gallagher on his blog.

    0 讨论(0)
提交回复
热议问题