Search code examples
iosobjective-cuibuttonexc-bad-access

How to set the titleLabel.text of a UIButton?


I would like to know how to do that properly because I am getting a Bad Access error.

In my app I have 81 UIButtons with an IBAction attached to all of them by Interface Builder, this IBAction should set the text of the button the user tapped on. I am trying to do that this way:

- (IBAction)changeTitle:(UIButton *)button {
    button.titleLabel.text = [NSString stringWithFormat:@"%@", myString];
}

-(IBAction)setMyString:(id)sender{
myString = [NSString stringWithFormat:@"text"];
}

However this comes into a Bad Access Error, how could I solve that? Million Thanks!

error message: EXC_BAD_ACCESS (code=1, address=0x0) (lldb)


Solution

  • You might have a memory management problem. You are not using a @property to set your instance variable. You are setting it manually so you have to manage the memory yourself.

    -(IBAction)setMyString:(id)sender{
        [myString release]; // release old instance
        myString = [[NSString stringWithFormat:@"text"] retain];
    }
    

    or even better, create a @property for your variable if you haven't done so already and set your variable by using the setter. Like this:

    @property (copy, nonatomic) NSString *string; // in your @interface
    @synthesize string = myString;                // in your @implementation
    
    -(IBAction)setMyString:(id)sender{
        self.string = [NSString stringWithFormat:@"text"]; // setter will release old value, and retain new value
    }
    
    - (IBAction)changeTitle:(UIButton *)button {
        // you should not set the text of the titleLabel directly
        [button setTitle:self.string forState:UIControlStateNormal];
    }