使用存储在变量中的类名来调用类方法? [英] Use a Class name stored in a variable to call a Class method?

查看:64
本文介绍了使用存储在变量中的类名来调用类方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能想太多了/浪费时间试图避免一些条件代码 - 所以我想我会问.我已经看到其他一些问题@此类,但他们使用的是 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.

这篇关于使用存储在变量中的类名来调用类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆