NSString 中的 Obj-C 变量?

发布于 2024-11-15 21:35:00 字数 656 浏览 2 评论 0原文

可能的重复:
从 NSString 获取 ivar 或属性
从 NSString 中删除 @“” 或将 NSString 类型转换为变量名

假设我有:

MyClass *myVar = [[MyClass alloc] init];

并且我有一个 NSString *myString = @"myVar";

有没有办法根据我拥有的字符串检索 var 的实例?

Possible Duplicates:
Get an ivar or property from a NSString
Remove @“” from NSString or typecast NSString into variable name

Let's say I have:

MyClass *myVar = [[MyClass alloc] init];

and I have an NSString *myString = @"myVar";

Is there any way to retrieve the instance of the var based on the string I have?

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

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

发布评论

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

评论(2

孤云独去闲 2024-11-22 21:35:00

在运行时,标识符 myVar 没有任何意义,它被内存中的地址替换。如果您希望能够通过名称获取对象,则需要使用 NSDictionary 或可变字典,例如

NSDictionary* map = [NSDictionary dictionaryWithObjectsAndKeys: 
                        [[[MyClass alloc] init] autorelease], @"myVar", nil];

然后按如下方式访问:

[map objectForKey: @"myVar"];

At run time the identifier myVar means nothing, it's replaced by an address in memory. If you want to be able to obtain objects by name, you need to use an NSDictionary or mutable dictionary e.g.

NSDictionary* map = [NSDictionary dictionaryWithObjectsAndKeys: 
                        [[[MyClass alloc] init] autorelease], @"myVar", nil];

Then access as follows:

[map objectForKey: @"myVar"];
太阳哥哥 2024-11-22 21:35:00

如果是实例变量,只需使用valueForKey:。如果它是局部变量,那么你就不走运了。如果它是全局的,你可以做到,但是它很丑陋,很慢并且乞求“为什么?!”的问题。


您必须提供有关您要做什么的更多信息。根据定义,局部变量仅在其定义的范围内有效。鉴于此,很难想象您需要象征性地访问局部变量而没有更好/更干净/更简单的方法的情况。

If it is an instance variable, just use valueForKey:. If it is a local variable, you are out of luck. If it is a global, you can do it, but it is ugly, slow and beg's the question of "why?!".


You'll have to provide more information as to what you are trying to do. By definition a local variable is only valid within the scope within which it is defined. Given that, it is hard to imagine a situation where you would need to access a local variable symbolically where there isn't also a better/cleaner/easier way.

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