views:

138

answers:

2

I have a switch statement similar to this one:

 switch (number)
 {
  case 1:
   if (imageView1.hidden == NO)
   {
    imageView1.hidden = YES;     

   } else 
   {
    imageView1.hidden = NO;
   }


   break;
  case 2:
   if (imageView2.hidden == NO)
   {
    imageView2.hidden = YES;


   } else 
   {
    imageView2.hidden = NO;
                            }

   break;

And so forth and so on.

My question is how do I use a string with a value say "imageView1" and use that to access the instance of my imageView class instead of having a different case for each instance of imageView? I know it muse be similar to creating an NSPath from a string or something like that, but I'm just not sure where to look or what it would be called.

Thanks in advance for any help!

+4  A: 

Why not put the instances in an NSArray and index into that?

NSArray *views = [NSArray arrayWithObjects: imageView1, imageView2, nil];
NSImageView *iview = [views objectAtIndex: number];

Also, you could consider something like:

iview.hidden = ! iview.hidden;

[Edit: missing asterisks, oops]

JimG
+5  A: 

I don't disagree with those who are concerned about the design, if this is actually the code. I will assume, however, that you are only posting a generalized version of your question. And since this is an important concept in Objective-C, so we should talk about it.

You can access an object's properties by name using Key Value coding, and the routine -valueWithKey:.

NSString *nameOfView = @"imageView1";
[[self valueForKey:nameOfView] setHidden:YES];

This will, in order, look for a method called -imageView1, an ivar named imageView1 and finally an ivar named _imageView1. This technique is very heavily used in Cocoa, and is important to understand. This is one of the many reasons we name things carefully, and yet another reason that we make accessors that handle memory management for us. Search the docs for "Key-Value Compliance" for more information.

Now for this specific case, I would tend towards something more like JimG's solution, using an NSArray of views, so I can loop through them and turn on or off the ones I want based on their index. But I can imagine a lot of cases where that wouldn't be appropriate, and KVC may be.

Rob Napier