开发者

Obj-C variable from NSString? [duplicate]

This question already has开发者_如何转开发 answers here: Closed 11 years ago.

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?


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"];


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜