开发者

Dynamically generated property/function call in objective C

开发者 https://www.devze.com 2023-01-10 04:06 出处:网络
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

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

精彩评论

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