Roohul Roohul - 1 year ago 67
Objective-C Question

How to access the property of own class with its name as a string

I am looking for a way to access one of my property from its name.
For example, I have 3 properties in a particular class as

@property (nonatomic, weak) UIImageView *image1;
@property (nonatomic, weak) UIImageView *image2;
@property (nonatomic, weak) UIImageView *image3;

And I have a method as

- (void)accessProperty:(NSString *)propertyName{
//image1, image2 or image3 will be passed here.
//how can I access the property with its name ?????

Any help will be appreciated.

Let me mention my need more precisely.
I have 3
but I want to set image to the particular imageView who's name matches with the name I passed to the method. For example if I will call the method as
[self accessProperty:@"image1"];
Then it should set image to

Answer Source

You want valueForKey. This is Key-Value coding (KVC):

for (NSUInteger i = 1; i <= 3; i++) {
    NSString *key = [NSString stringWithFormat:@"image%u", i];
    UIImageView *value = [self valueForKey:key];

Note: I have assumed the properties are string1, string2 and string3; not all string1.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download