Static initializer in Objective-C upon Class Loading

走远了吗. 提交于 2019-12-06 13:32:23

You want to use NSClassFromString, like this:

Class klass = NSClassFromString(@"MyClass");
id obj = [[klass alloc] init];
Quinn Taylor

First, there is indeed such an equivalent in Objective-C — as @Louis suggested, use NSClassFromString().

Second, if you want a static constructor like in Java, you can do that as well with the +initialize method. See this related SO question.

You can also say

Class myClass = [[NSBundle mainBundle] classNamed: @"MyClassName];
id myInstance = [[myClass alloc] init];

This frequently helps with cases when the runtime may not have come across your class yet.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!