0

I'm new to Objective-C and want to be able to attach an integer attribute to each physical button I can see in Interface Builder; I'll also need many other variables so just using the 'Tag' attribute is not sufficient. I've created a sub-class but can't seem to alter these new variables from instances of this class.

myButton.h---------

@interface myButton : UIBUtton
{
    int hiddenNumber;
}

@property(nonatomic, assign) int hiddenNumber;


myButton.m--------
#import "myButton.h"

@implementation myButton
@synthesize hiddenNumber;


ViewController.h-------
IBOutlet myButton *button1; // This has been connected in Interface Builder.

ViewController.m-------
[button1 setAlpha:0]; // This works (one of the built-in attributes).
[button1 setHiddenNumber:1]; // This won't (one of mine)! It receives a 'Program received signal: "SIGABRT".

Any help would be great, thanks.

2 Answers2

3

In Interface Builder you will have to set the type of the Button to your custom button.

Under "Identity Inspector" is Custom Class. Set that from UIButton to myButton.

MarkPowell
  • 16,482
  • 7
  • 61
  • 77
1

The problem with subclassing UIButton just to add properties to store data is you end up limiting yourself to only the custom button type. No more rounded rect for you since these buttons are part of class cluster. My recommendation? use Associative References. Take a look at this post Subclass UIButton to add a property

UIButton+Property.h

#import <Foundation/Foundation.h>

@interface UIButton(Property)

@property (nonatomic, retain) NSObject *property;

@end

UIButton+Property.m

#import "UIButton+Property.h"
#import <objc/runtime.h>

@implementation UIButton(Property)

static char UIB_PROPERTY_KEY;

@dynamic property;

-(void)setProperty:(NSObject *)property
{
    objc_setAssociatedObject(self, &UIB_PROPERTY_KEY, property, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(NSObject*)property
{
    return (NSObject*)objc_getAssociatedObject(self, &UIB_PROPERTY_KEY);
}

@end
Community
  • 1
  • 1
Joe
  • 56,979
  • 9
  • 128
  • 135
  • Hi Joe, thanks for the answer, excuse my ignorance at this but what disadvantages are there to not being able to use 'rounded rect' buttons? – indoorGinger Apr 20 '11 at 07:16
  • None if you never want to use them. You are essentially locking your self into a custom `UIButton` and can not use your custom properties with any of the `+(id)buttonWithType:(UIButtonType)buttonType` methods in the future because they return different button types from the class cluster. Also you do not have to change your custom class inside of interface builder to use the properties. Just include the category header in your source file. – Joe Apr 20 '11 at 12:53