开发者

Set/Reset instance variables based on what button UIButton selector call

I have a set of class instances which have a BOOL instance variable called x. When a button is clicked I need x to be set to NO for all instances except the instance related to the button that triggered the method. Kind of like how a radio button works.

It’s easy to set all the instances of the x to variables to NO. I need help determining how to set, for example, cInstance.x to YES. myMethod will be used by many different buttons with will relate to different instances.

I can write it with three separate methods that the selectors call however this screams bad programming.

[myButtonA addTarget:self action:@selector(myMethodA:) forControlEvents:UIControlEventTouchUpInside];
[myButtonB addTarget:self action:@selector(myMethodB:) forControlEvents:UIControlEventTouchUpInside];
[myButtonC addTarget:self action:@selector(myMethodC:) forControlEvents:UIControlEventTouchUpInside];


    - (void)myMethodA:(id)sender {
     NSArray *objects = [NSArray arrayWithObjects:aInstance, bInstance, cInstance, dInstance, eInstance, nil];
     int i = [objects count];
     while (i--) {
      MyClass *selectedInstance = [objects objectAtIndex:i]; 
      selectedInstance.x = NO;
     }
     aInstance.x = YES; 
    }

    - (void)myMethodB:(id)sender {
     NSArray *objects = [NSArray arrayWithObjects:aInstance, bInstance, cInstance, dInstance, eInstance, nil];
     int i = [objects count];
     while (i--) {
      MyClass *selectedInstance = [objects objectAtIndex:i]; 
      selectedInstance.x = NO;
     }
     bInstance.x = YES; 
    }

    - (void)myMethodC:(id)sender {开发者_运维问答
     NSArray *objects = [NSArray arrayWithObjects:aInstance, bInstance, cInstance, dInstance, eInstance, nil];
     int i = [objects count];
     while (i--) {
      MyClass *selectedInstance = [objects objectAtIndex:i]; 
      selectedInstance.x = NO;
     }
     cInstance.x = YES; 
    }

Now I suppose I could create a new method to reset all x variables to NO, then have a separate method for each button which sets a specific variable to YES however this kind of thing should only require one method total.


Well, let's say you have an array with pointers to all your instances (is MyClass a subclass of UIButton? I'm assuming that here) that have the x property:

NSArray* myButtons = [[NSArray alloc] initWithObjects:button1, button2, ..., nil];

Now, let's suppose you have all your TouchUpInside events for all those buttons set to call this buttonPressed method. This loop goes thru all the buttons and sets the all to NO except for the one that was just pressed (sender):

-(void) buttonPressed:(id)sender 
{
    for (MyClass* button in myButtons) {
        button.x = (button == sender);
    }
}

All the button's x properties are set to NO except for the sender (the one pressed).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜