开发者

Convert string into variable

If in a class, I have a instance variable: nsstring *foo开发者_JS百科, now I want a create a variable with a string @"foo".

Example: I have the string @"foo", and with this string, I want a do: myobject.foo.


I think what you are looking for is KVC Key-Value Coding.

It enables you to retrieve or set a property or an instance variable on an object by it's name (a String). You can do something like:

id fooValue = [myobject valueForKey:@"foo"];
[myobject setValue:barValue forKey:@"foo"];


If you have setter and getter methods (or have synthesized them), you could use NSSelectorFromString() to access and modify your variable.

Accessing:

id foo = [self performSelector:NSSelectorFromString(@"foo")];

Modifying:

[self performSelector:NSSelectorFromString([NSString stringWithFormat:@"set%@:, [@"foo" capitalizedString]]) withObject:foo];
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜