本文介绍了在Obj-C中发现给定类的子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何方法可以在运行时发现给定类的子类存在?

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

编辑:到目前为止,我认为我需要澄清我要做的事情.我知道这在可可粉中并不常见,可能会有一些警告.

From the answers so far I think I need to clarify a bit more what I am trying to do. I am aware that this is not a common practice in Cocoa, and that it may come with some caveats.

我正在使用动态创建模式编写一个解析器. (请参见Buck和Yacktman的《可可设计模式》一书,第5章.)基本上,解析器实例处理堆栈,并实例化知道如何执行某些计算的对象.

I am writing a parser using the dynamic creation pattern. (See the book Cocoa Design Patterns by Buck and Yacktman, chapter 5.) Basically, the parser instance processes a stack, and instantiates objects that know how to perform certain calculations.

如果可以获取MYCommand类的所有子类,则可以为用户提供可用命令列表.另外,在第5章的示例中,解析器具有替换字典,因此可以使用+,-,*和/之类的运算符. (它们映射到MYAddCommand等.)在我看来,该信息属于MyCommand子类,而不是解析器实例,因为它有点违反了动态创建的思想.

If I can get all the subclasses of the MYCommand class, I can, for example, provide the user with a list of available commands. Also, in the example from chapter 5, the parser has an substitution dictionary so operators like +, -, * and / can be used. (They are mapped to MYAddCommand, etc.) To me it seemed this information belonged in the MyCommand subclass, not the parser instance as it kinda defeats the idea of dynamic creation.

推荐答案

而不是尝试自动注册MYCommand的所有子类,为什么不将问题分成两部分?

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

首先,提供用于注册类的API,例如+[MYCommand registerClass:].

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

然后,在MYCommand中创建代码,这意味着所有子类都将自动注册自己.像这样:

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

@implementation MYCommand
+ (void)load
{
    [MYCommand registerClass:self];
}
@end

这篇关于在Obj-C中发现给定类的子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-08 04:46