Jean Paul
Jean Paul

Reputation: 2439

Creating a button programmatically

I have seen 2 ways to create button.

UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(10, 220, 150, 30)];

and

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];

The first case is the normal way to create a button object. I have allocated and initialised a button instance and I have to release that. I am really confused about the second way. I have some questions regarding this.

  1. Is a button instance created in this case?
  2. What is the retain count of this button?
  3. Should I release this button?

Upvotes: 0

Views: 458

Answers (4)

Piyush Kashyap
Piyush Kashyap

Reputation: 1965

1.)Yes the button instance will be created whether you allocate it or by using factory method.In both the cases button instance will be created

2.)The retain count will be 1 for the current run loop/cycle,Then on the next loop, the object will be auto released. Thus the retainCount will be 0. (Note: NSLogging a retainCount of 0 will crash the app)

3.)No you don't have to release the button created with factory methods,They are released automatically .

Upvotes: 0

user1181985
user1181985

Reputation: 19

From: http://cocoadevcentral.com/d/learn_objectivec/

On local memory management:

There's only one rule: if you create an object with alloc or copy, send it a release or autorelease message at the end of the function. If you create an object any other way, do nothing.

  1. Yes a local instance is created
  2. 1, but will be 0 when the function ends
  3. No, the object will be marked for release when the function ends provided you don't call retain on it.

Upvotes: 1

Janak Nirmal
Janak Nirmal

Reputation: 22726

Hope this helps:

  1. Yes button instance is created.
  2. Retain count will be how do you add/retain.
  3. You don't need to release button if you have not created it by alloc.

Upvotes: 7

El Developer
El Developer

Reputation: 3346

Is a button instance created in this case?

Yes, an instance is created.

What is the retain count of this button?

The retain count is probably one, otherwise the lifecycle would get rid of it.

Should I release this button?

No, you shouldn't the object is autoreleased.

Upvotes: 2

Related Questions