views:

199

answers:

2

I'm trying to add a UIButton with code (not Interface Builder).

Some examples say you MUST alloc and release memory for the button.

Others use buttonWithType and magically create a button without alloc'ing any memory at all.

How is that possible?

(Both seem to work fine.)

Which of the 2 methods do I want to use... and when? Are there some huge benefits to 1 method or another?

PLEASE don't tell me to just go "read the docs". The docs are the REASON I am here. They rarely seem to explain things without leaving out tons of 'missing info'.

A: 

Both works. The +buttonWithType: method is a convenient method, which is similar to

[[[UIButton alloc] initWithType:type] autorelease];

Since it is already -autorelease'd, you cannot -release it.

For built-in buttons (e.g. rounded rectangular, info buttons, etc.), you must use +buttonWithType: because there is no other ways to create them. Otherwise, both choices are fine.

KennyTM
For "rounded rectangular" you must use +buttonWithType.....................................Really? I didn't know that either. So there *ARE* reasons/places to use 1 method... and not the other?
Bonnie
@Jill: Yes, but that's *not* because of memory stuff. BTW, `-initWithType:` does not exist, in case someone wonders.
KennyTM
+2  A: 

buttonWithType: does use memory, but it is autoreleased. This means that it will be released at some point in the future. So [UIButton buttonWithType:] is equivalent to [[[UIButton alloc] initWithFrame:] autorelease].

You can use either method, depending on whether you want to be explicit or not about releasing.

Colin Gislason