如何命名 obj-c 函数来调用 xml 数据
新手问题在这里。我希望能够通过数据(即 XML 文件)指定要发送的适当的 Objective-C 消息。关于这是否可能或我该如何做到这一点有什么建议吗?
如果我做不到这一点,下一个最好的事情就是创建一个映射对象,将键(int)与函数(我猜也是选择器)相关联。如果以上都不行,那还可以吗?
如果有人可以向我指出一些教程或示例代码作为参考,那就太好了。现在我正在使用一个大的 switch 语句来做事情,但我不喜欢它。 (我正在打开 id,并且在每种情况下,显式调用与特定 id 相关的方法。)
Newbie question here. I'd like to be able to specify through data (i.e. an XML file), the appropriate Objective-C message to send. Any advice on if this is possible or how I can do this?
The next best thing, if I can't do this, would be some way to create a map object that would correlate a key (an int
) with a function (I guess also a selector). Is that possible if the above isn't?
If someone could point me to some tutorial or example code as reference, that'd be great. Right now I'm doing things with a big switch statement, and I don't like it. (I'm switching on the id and in each case, explicitly calling the method relevant to the particular id.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我喜欢你问这个问题;我经常看到撒旦膨胀的开关声明。很高兴看到有人想要使用函数表来代替。
如果您可以使用属性列表文件(通常以 XML 编码),那么这非常简单。
只需创建一个属性列表,其中根元素是字典,它从某些键映射到某些选择器。
将属性列表的内容加载到 NSDictionary 中:
当然,您需要将此逻辑重构为适当的方法,并且可能将属性列表缓存为实例变量。
注意:我个人认为最好将这个函数表内联起来;属性列表很酷,但我不确定它在这种情况下是否很有帮助。另外,如果您喜欢使用 Objective-C++,
std::map
将允许您不必在NSString
对象等中包装和展开选择器。< /em>I love that you asked this question; too often, I see Satan's Swollen Switch Statement. It's nice to see someone wanting to using a function-table instead.
If you're OK with using a property list file (which is usually encoded in XML), this is really easy.
Just make a property list where the root element is a dictionary, which maps from some keys to some selectors.
Load the contents of your property list into an
NSDictionary
:Of course, you'll want to refactor this logic into an appropriate method, and probably cache the property list as an instance variable.
Note: I personally think it's better to just put this function table inline; property lists are cool, but I'm not sure that it is very helpful in this case. Also, if you are cool with using Objective-C++,
std::map
will allow you to get away with not wrapping and unwrapping the selectors inNSString
objects, etc.