Create a UIButton with (or without) memory

2019-07-13 13:05发布

问题:

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'.

回答1:

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.



回答2:

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.



回答3:

There are two memory management method in Cocoa: reference count and autorelease.

According to the Memory Management Policy in Cocoa,

You own any object you create

You create an object using a method whose name begins with “alloc”, “new”, “copy”, or “mutableCopy” (for example, alloc, newObject, or mutableCopy).

buttonWithType has none prefix as mentioned above, so you have not own of the button created by buttonWithType. In fact, buttonWithType use the anther method, autorelease, to release the created button.