Objective C object by string name?

和自甴很熟 提交于 2019-12-07 17:57:34

It could be possible if you stored named objects as properties or in some sort of dictionary. Then you could do something like this:

// Put object into dictionary
[dictionaryWithObjects setValue:someNamedObject forKey:@"someNamedObject"];

// and then retrieve it
id object = [dictionaryWithObjects valueForKey:@"someNamedObject"];

And I'm not sure ObjectiveC supports that level of metaprogramming.

It doesn't look quite as it does in PHP but, yes, it is possible to get a class from a string. You use the NSClassFromString function.

For example the following two lines are equivalent:

id a = [[NSClassFromString(@"NSString") alloc] init];
id a = [[NSString alloc] init];

You can use NSClassFromString() to get a class, but for specific instances of an object I don't think this is possible.

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