glabber
glabber

Reputation: 23

how to get class member object by it's string name?

If I have a class member of lets say UIImageView in my viewcontroller :

UIImageView* imageView = self.memberImageView1;

Is there a way I can get this member by string ? somthing like :

UIImageView* imageView =[self.getMember(@"memberImageView1")];

Of course I'm talking about solution with objective-c syntax, and not custom. Thanks.

Upvotes: 2

Views: 965

Answers (3)

Rich Pollock
Rich Pollock

Reputation: 1190

Just for completeness, a full-on crazy way to do this would be as follows:

UIImageView *imageView;

SEL selector = NSSelectorFromString(@"memberImageView1");
NSMethodSignature *signature = [self instanceMethodSignatureForSelector:selector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];

[invocation setSelector:selector];
[invocation setTarget:self];
[invocation invoke];
[invocation getReturnValue:&imageView];

Please feel free to cross-post to the Daily WTF.

Upvotes: 1

Joe
Joe

Reputation: 57169

I recommend Key Value Coding before reflection.

UIImageView* imageView =[self valueForKey:@"memberImageView1"];

Upvotes: 6

Jim
Jim

Reputation: 3294

To do this kind of thing you can use reflection:

Objective-C Runtime Reference

The other way is to use a Dictionary with a string as a key pointing to the class variable.

Upvotes: 1

Related Questions