Is there a way to get a class by name?

爷,独闯天下 提交于 2019-12-01 04:12:37

问题


In Objective-C, is there a way to get a class and send messages to it when you have the name of the class as a string? For example, is there a function func where func(@"NSString") == [NSString class]?

The reason that I want to know this is I am building a dynamic linker library for a language I am working on, and I want it to have an interface to Objective-C libraries.


回答1:


Yes — two, in fact. If you have a Foundation-type framework (e.g. from Cocoa, Cocoa Touch or GNUstep), you can use the NSClassFromString() function, which is precisely the same as your func. If you do not want to depend on a framework, there's a similar runtime function, objc_getClass(), that takes a const char* and returns the named class (or nil if none is found).




回答2:


You can use NSClassFromString(NSString className) to get the class object from its name.

Hope this helps!



来源:https://stackoverflow.com/questions/4180810/is-there-a-way-to-get-a-class-by-name

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