使用存储在变量中的类名来调用类方法?

编程入门 行业动态 更新时间:2024-10-27 12:37:56
本文介绍了使用存储在变量中的类名来调用类方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

使用存储在变量中的类名来调用类方法?

本文发布于:2023-11-11 23:53:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1579900.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   方法   类名来

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!