我可能想太多了/浪费时间试图避免一些条件代码 - 所以我想我会问.我已经看到其他一些问题@此类,但他们使用的是 php 或其他语言.
I'm probably over-thinking this/wasting time trying to avoid a bit of conditional code - so I thought I would ask. I've seen some other questions @ this sort of thing but they were using php or some other language.
最基本的,我可以做这样的事情吗(我知道语法是错误的):
At the most basic, can I do something like this (I know the syntax is wrong):
Class * var = @"Playback_Up"; // call Class method to get default settings NSMutableDictionary * dict = [var getPlaybackDefaults];我为什么要这样做?避免一堆条件.我有一个应用程序,用户可以从一系列播放类型"中进行选择——每种类型都由播放"类的子类处理.将类名存储在数组中,然后在进行选择时(从 tableView)调用所选类,创建它的实例等会很方便.
Why do I want to do this? To avoid a bunch of conditionals. I have an app where a using can select from a range of playback "types" - each type is handled by a subclass of a "Playback" class. It would be convenient to store the class names in an array and then when a selection is made (from a tableView) call the selected class, create an instance of it, etc.
这是可能的还是我在这里挖了个坑?
Is this possible or am I digging myself into a hole here?
推荐答案第一行的正确语法是:
Class var = NSClassFromString(@"Playback_Up");其他都很好,我使用这种技巧的频率比你想象的要高.
The rest is fine, and I use this kind of technique more frequently than you might imagine.
(当然,Playback_Up"不应该是类的名称.)
(Except that "Playback_Up" should never be the name of a class of course.)
请注意下面 Paul.s 的评论.如果您可以在编译时对类进行硬编码,最好使用 +class.
Do note Paul.s's comment below. Using +class is preferred if you can hard-code the class at compile time.
更多推荐
使用存储在变量中的类名来调用类方法?
发布评论