Objective C 动态对象创建

发布于 2024-08-20 00:18:57 字数 321 浏览 3 评论 0原文

快速问你一个问题。我希望能够创建对象的实例。对象类型基于字符串。

在 php 中,你可以用字符串替换类名,但我怀疑在 Objective c 中是否那么容易。

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

这是它可能是什么样子的细分。我想尝试避免使用巨大的 case 风格的语句。

是否可以使用选择器系统来实现此目的?

有什么想法吗?

干杯

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

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?

any ideas?

Cheers

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

无戏配角 2024-08-27 00:18:57

您可以使用 NSClassFromString() 动态获取 Class 对象

Class c = NSClassFromString(@"ClassName");
id obj = [[c alloc] init];

You can get a Class object dynamically with NSClassFromString()

Class c = NSClassFromString(@"ClassName");
id obj = [[c alloc] init];
凑诗 2024-08-27 00:18:57

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

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

因此您的代码可能如下所示(但尚未测试):

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

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];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文