0

Possible Duplicate:
Objective C Equivalent of PHP’s “Variable Variables”

I have a UIButton action, that grabs the button sender

This line gives me the sender tag which I'm using in a switch statement

int senderTag = [sender tag];

I then have to do...

switch (senderTag) {
    case 1:
       brain.selectedPaintColor1 = myColor;
       break;
    case 2:
       brain.selectedPaintColor2 = myColor;
       break;
    case 3:
       brain.selectedPaintColor3 = myColor;
       ...

What I'd really like to be able to do is use the tag to set a variable property name like this

[brain.selectedPaintColor%i,senderTag] = myColor;

Can anyone assist with the syntax to be able to do that?

Thanks!

Community
  • 1
  • 1
sayguh
  • 2,540
  • 4
  • 27
  • 33

3 Answers3

2

Direct translation of what you want

NSString *key = [NSString stringWithFormat:@"selectedPaintColor%i", senderTag];

[brain setValue:myColor forKey:key];
Paul.s
  • 38,494
  • 5
  • 70
  • 88
1

Or, since the assignment methods above are really being translated into calls to setter methods, one could build an array of selectors and call a method from the indexed array. (Not going to slog through the syntax just now though -- selectors always make my head hurt.)

(And, in fact, there's a way to dynamically look up a selector, so you could build the selector name string and look it up, vs pre-constructing an array.)

Hot Licks
  • 47,103
  • 17
  • 93
  • 151
0

Combine your properties selectedPaintColor1 , selectedPaintColor2 etc. into an NSMutableArray and use that as a property. Now the syntax is:

[brain.paintColors replaceObjectAtIndex:sender.tag withObject:myColor];

Be aware that if your sender is of type id you will have to cast it into a (UIView) first.

Mundi
  • 79,884
  • 17
  • 117
  • 140