NSString 中的 Obj-C 变量?
可能的重复:
从 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在运行时,标识符 myVar 没有任何意义,它被内存中的地址替换。如果您希望能够通过名称获取对象,则需要使用
NSDictionary
或可变字典,例如然后按如下方式访问:
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.Then access as follows:
如果是实例变量,只需使用
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.