0

I trying to extend UIButton but I keep getting a "EXC_BAD_ACCESS", inside the initializer of ColorButton's implementation file.

Header of ColorButton.

#import <Foundation/Foundation.h>


@interface ColorButton : UIButton {
    UIImage * originalImage;
}

@property (nonatomic,readonly) NSString * buttonName;

-(id) initButtonWithName:(NSString *) color;
-(void) setOriginalImage;
-(void) setImage:(UIImage *) image;
@end

ColorButton Implementation

#import "ColorButton.h"

@implementation ColorButton

@synthesize buttonName;

-(id) initButtonWithName:(NSString *) color {
    if ((self = (ColorButton *)[UIButton buttonWithType:UIButtonTypeCustom])) {
        buttonName = color;
        [self setTitle:buttonName forState:UIControlStateNormal]; //This is the line of the "EXC_BAD_ACCESS" error.
        [self setBackgroundImage:[self backgroundImageForDevice:color] forState:UIControlStateNormal]; // This line gets the error too. If I comment the line before it out.
    }
    return self;
}

-(UIImage *) backgroundImageForDevice:(NSString *) color {
        color = [color stringByAppendingString:@"Bubble"];
    if ([[[UIDevice currentDevice] model] isEqualToString:@"iPad"] ||[[[UIDevice currentDevice] model] isEqualToString:@"iPad Simulator"]) {
        color = [color stringByAppendingString:@"-iPad"];
    }
    color = [color stringByAppendingString:@".png"];
    return [UIImage imageNamed:color];
}

-(void) setOriginalImage {
    [self setBackgroundImage:originalImage forState:UIControlStateNormal];
}

-(void) setImage:(UIImage *) image {
    [self setImage:image forState:UIControlStateNormal];
}
@end
user828267
  • 303
  • 4
  • 9

1 Answers1

2

You can not cast a UIButton * instance to a ColorButton * type.

You have to remember that you ColorButton inherits from UIButton and not the other way, this means that every instance of ColorButton is a UIButton by definition, but the opposite is not true.

Here is another thread that has the exact same issue :)

objective C: Buttons created from subclass of UIButton class not working

Community
  • 1
  • 1
Felipe Sabino
  • 17,825
  • 6
  • 78
  • 112