iphone – Is there any way to create a UIButton which is not autoreleased, and still set it’s UIButtonType? – Education Career Blog

UIButton has a single initializer buttonWithType. But this is a factory method and will create an autoreleased object. Of course we can do something like:

 UIButton *button = UIButton alloc initWithFrame:CGRectMake(10, 10, 50, 30);

But in this case i will not be able to set the button’s type as buttonType is a read only property.

So is there any way i can create buttons which are not autoreleased and still set their type?

P. S. :

  1. Using AutoreleasePool with the autoreleased objects is a good practice. But i don’t really have a problem with autoreleased objects. This is just a doubt.

  2. I am not looking for solution for any particular scenario so please don’t reply with questions like “Why do you want this?”. It just occurred to me that this is something i am not able to do.. so i am asking..

Thanks,
Swapnil

,

You can use the initializer and later send the object a retain message if you still need it.

I think that the reason for the lack of other initializers is that UIButtons are typically added as a subview somewhere and thus receive a retain message automatically.

,

No, only +buttonWithType: can create those special buttons. The reason why there isn’t an +alloc/-init pair to construct such button is because they are actually implemented by some private subclass (e.g. UIRoundedRectButton).

If you need to retain the button, use -retain.

theButton = UIButton buttonWithType:foo retain;

Leave a Comment