2

I'm new to Objective-C so sorry if this is a newbie question. I've searched for a couple of hours and can't seem to find an answer to my question.

So I'm trying to access a UIImageView so I can hide/unhide it by concatenating strings together to get the name of the UIImageView which should hide/unhide.

I have it working by doing:

self.faceItemEyesFrightened.hidden = false;

However the Frightened part of the name could be different each time a button is clicked so, trying to refactor my code I run a function which returns the type of UIImageView should be affected.

So I have the following:

NSString *fullEmotionString = [@"faceItemEyes" stringByAppendingString:emotionIs];

where emotionIs would be Frightened, therefore forming

faceItemEyesFrightened

So my problem comes when I wish to do something like this:

self.fullEmotionString.hidden = false;

Obviously that's not the right way of doing it but I'm not sure how it should be done, any advice greatly appreciated. Cheers!

Daij-Djan
  • 49,552
  • 17
  • 113
  • 135
Martin
  • 176
  • 1
  • 14

1 Answers1

0

You could use NSSelectorFromString like this:

SEL selector = NSSelectorFromString(fullEmotionString);
UIImageView *imageView = [self performSelector:selector];
imageView.hidden = NO;

Note, that this requires a getter called faceItemEyesFrightened to be defined, which is usually this case if you're using properties and didn't change the name of the accessors.

That being said, I think this is not an optimal solution to your problem. You could for instance subclass UIImageView and add an enum MyImageViewEmotion that describes the emotion in the image. Then, instead of using lots of variables, like faceItemEyesFrightened or faceItemEyesHappy, you could put all of them in a simple array and then get one of them like this:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.emotion == %ld",
                            MyImageViewEmotionFrightened];
MyImageView *imageView = [eyeImageViews filteredArrayUsingPredicate:predicate][0]

Of use an NSDictionary, where you put the emotion string as the key and the image views as the value. Then you could access them very easily:

UIImageView *imageView = emotionViewDictionary[@"Frightened"]; 

By the way, boolean values in Objective-C are called YES and NO and not true and false.

DrummerB
  • 39,814
  • 12
  • 105
  • 142
  • Perfect :) Thanks for the fast response. It is coming up with the warning `PerformSelector may cause a leak because its selector is unknown` however [this post](http://stackoverflow.com/questions/10793116/to-prevent-warning-from-performselect-may-cause-a-leak-because-its-selector-is) deals with this. Thanks again! – Martin Dec 04 '12 at 15:05
  • You're welcome. I added some alternative suggestions to your problem. – DrummerB Dec 04 '12 at 15:10