且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-05-17 08:55:58

第一行的正确语法是:

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.