0

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 imageView 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 imageView1 only

Roohul
  • 1,009
  • 1
  • 15
  • 26
  • 1
    I believe properties are having `IBOutlet` otherwise `weak` object will be release after initialisation. To access your property with name use `[self valueForKey:propertyName]` KVC it will return whole object. – Dipen Panchasara Jun 29 '16 at 13:11
  • [Access ObjC property dynamically using the name of the property](http://stackoverflow.com/q/1969897) does tell you how you can do this, but [the other question](http://stackoverflow.com/questions/21210228/using-a-string-as-name-to-set-property-values?lq=1) gives you more important information: _why you shouldn't_ and what to do instead. See also: [Create multiple numbered variables based on a int](http://stackoverflow.com/q/2231783) – jscs Jun 29 '16 at 18:19

1 Answers1

1

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];
}
Droppy
  • 9,691
  • 1
  • 20
  • 27