Create a UIButton with (or without) memory

淺唱寂寞╮ 提交于 2019-12-23 18:45:34

问题


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.



来源:https://stackoverflow.com/questions/2281966/create-a-uibutton-with-or-without-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!