开发者

Dynamic VariableFromString in objective C

I want to dynamically create variable from string in objective C.

Like NSClassFromString thats way. In that I want to acc开发者_JS百科ess variable.

Any idea about this?


If you want to dynamically access a property of an object, that's easy to do using Key Value Coding.

If your class is KVC-compliant (most Apple classes are), then use the valueForKey:, or valueForKeyPath: method to access a property as a string.

Consider this example.

// Shoe.h
@interface Shoe {
    NSString *brand;
    NSNumber *size;
}

@property (nonatomic, copy) NSString *brand;
@property (nonatomic, retain) NSNumber *size;

@end

// Shoe.m
@implementation 

@synthesize brand, size;

@end

Let's create and initialize a Shoe object first.

Shoe *someShoe = [[Shoe alloc] init];
someShoe.brand = @"Adidas";
someShoe.size = [NSNumber numberWithFloat:9.5];

Considering this example someShoe object, its brand or size can be accessed via a string.

NSString *brandName = [someShoe valueForKey:@"brand"];
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜