需要关于NSClassFromString的建议 [英] need advise about NSClassFromString

查看:67
本文介绍了需要关于NSClassFromString的建议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据此代码我不了解NSClassFromString

according to this code i dont understand about NSClassFromString

我怎么知道"viewControllerName"我可以从其他来源使用它吗?

how did i know "viewControllerName" can i use it from another source ?

能否请您告诉我更多有关如何使用NSClassFromString的信息?

could you please tell me more information how to use NSClassFromString?

UIViewController *viewController = [[NSClassFromString(viewControllerName) alloc] init];

推荐答案

NSClassFromString基于它的名称作为字符串返回一个Objective-C类(函数名称实际上是自解释的)...

NSClassFromString returns an Objective-C class based on it's name as a string (The function name is really self explanitory)...

您传入的字符串是您要创建的类的名称,例如:

The string you pass in is the name of the class you want to create, for example:

如果您有一个名为MyViewController的类,并且想从该字符串中获取Objective-C类,则可以使用此函数,例如 NSClassFromString(@"MyViewController");

If you have a class called MyViewController and you want to get an Objective-C class from that string, you use this function, like NSClassFromString(@"MyViewController");

通常,只有在测试可能无法使用的类名时(例如,同时编写针对iPhone OS 2.0和3.0的代码时),才需要执行此操作.

Normally you only need to do this when testing for class names that may not be available to you, for example, when writing code that targets iPhone OS 2.0 and 3.0 simultaneously.

如果使用该类作为符号,则该类将在以前版本的OS中不存在时崩溃.因此,您可以使用此函数使用该字符串返回一个类,如果成功返回该类,则知道该类存在并且可以安全使用,否则,如果返回 nil ,则该类不会不存在,您不应该使用它,并且您的程序应该采取步骤以在这种情况下正常运行.

If you use the class as a symbol, it'll crash if the class doesn't exist on the previous version of the OS. So you use this function to return a class using that string, and if the class is successfully returned, you know that it exists and is safe to use, else if it returns nil, then the class doesn't exist, you shouldn't use it and your program should take steps to behave properly in this situation.

这篇关于需要关于NSClassFromString的建议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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