I need to subclass UIButton, however the design of UIButton makes this really painful. This is because to create a button you really need to call:

[UIButton buttonWithType:UIButtonTypeRoundedRect]

So if I want to subclass I really need to do whatever it is this method does. However, it is not possible to set the buttons underlying type.

One option is to use something like decorator and subclass UIButton but have the actual button as an ivar and defer all property/method calls to this button. The problem here is that I then need to implement most of the UIButton interface (yawn).

What I have done is something a bit sneakier in my sub class. I have created this method:

- (id) initWithType:(UIButtonType)buttonType
    [super init];

    actualButton = [[UIButton buttonWithType:buttonType] retain];

    memcpy(self, actualButton, sizeof(UIButton));
    self->isa = [ABDescriptorButton class];

    return self ;

I know this is pretty unorthodox, but it works and is fairly clean in terms of code. What are the pitfalls I might have with this approach?


You don't need to make an initWithType: method. Just override the buttonWithType: factory method.

  • \$\begingroup\$ The problem is I want to create instances of my subclass. If I override the factory method the only way I can create instances of my sub class to return is by calling initWithType on them. \$\endgroup\$
    – Ian1971
    Apr 18 '11 at 8:34
  • 1
    \$\begingroup\$ Actually you are right. If I override + (UIButton *) buttonWithType:(UIButtonType)buttonType it actually returns an instance of the subclass. I assumed because the return was UIButton it would return a UIButton not the subclass. TIL that you can call [self alloc] in a factory method which will ensure that overridden classes get created with the subclass type. I guess I am not used to even being able to override static methods. \$\endgroup\$
    – Ian1971
    Apr 19 '11 at 9:03

I think I've realised the problem myself. Memory management gets very confused because we are now essentially tracking two objects that are actually the same object.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.