客观c动态对象创建 [英] objective c dynamic object creation

查看:172
本文介绍了客观c动态对象创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为您提供快速问题。我想要能够创建一个对象的实例。对象类型基于字符串。

Quick question for you. I want to be able to create an instance of an object. The object type is based of a string.

在php中,你可以用一个字符串替换类名,但我怀疑这在Objective c中很容易。 p>

In php you can just replace the class name with a string, but I doubt it is that easy in Objective c.

NSString * className;
id theObject;
className = @"TestObject";
theObject = [[className alloc] init];

这里是它可能看起来的分解。

here is a break down of what it might look like. I want to try and avoid using a giant case style statement.

可以使用选择器系统吗?

Is it possible to use the selector system for this?

任何想法?

干杯

推荐答案

使用以下obj-c运行时函数之一获取类名(可能需要导入标题:

You can get a class by its name using one of the following obj-c runtime functions (you may need to import header:

id objc_lookUpClass(const char *name)
id objc_getClass(const char *name)

可能看起来像(未测试它):

So your code may look like (have not tested it though):

NSString * className = @"TestObject";
id theObject = nil;
Class myClass = objc_lookUpClass([className UTF8String]);
if (myClass)
   theObject = [[myClass alloc] init];

这篇关于客观c动态对象创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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