开发者

Dynamically generated property/function call in objective C

Is it possible to dynamically build a property or function call? I have a set of views I want to render in the same manner. So if part of my code is like this

self.ViewName.hidden = NO;

and I want to use a variable for the name of the view, is there a way to do it, something like

self{var}.hidden = NO;

Where 'var' is a NSString of the view name and evaluated at runtime? I know t开发者_如何学Gohis won't work with the angle brackets, just to give of how I am trying to build the property reference.

Thanks


You can dynamically get a selector at run time using the NSSelectorFromString function. So if you wanted to get the viewName based on a string you would use

[[self performSelector:NSSelectorFromString(@"ViewName")] setHidden:NO];


You can use setValue:forKeyPath: method:

NSString* path = [NSString stringWithFormat:@"%@.hidden", viewName];
[self setValue:[NSNumber numberWithBool:YES] forKeyPath:path];


If you have multiple views, you should put them in an array and access each element of the array separately.

NSMutableArray * views...
[[views objectAtIndex:i] setHidden:NO];
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜