0

Hey all, this is something I've wondered about for a while and never really figured out. If I allocate and initialize another class's instance variable/property (example below), am i responsible for releasing it?

In Foo, I have an instance of Bar (called bar) and want to init one of Bar's variables like so:

self.bar.variable1 = [[UIBarButtonItem alloc] initWithCustomView:customView];

4 Answers 4

4

Foo is responsible for releasing the UIBarButtonItem it creates because Foo owns it. This can be done simply by sending an autorelease message to the UIBarButtonItem. Otherwise, this will leak.

self.bar.variable1 = [[[UIBarButtonItem alloc] initWithCustomView:customView] autorelease];

If Bar needs to keep variable1 around, it must claim ownership of the UIBarButtonItem. Bar is responsible for retaining (and then releasing at some point in the future) the UIBarButtonItem itself.

Sign up to request clarification or add additional context in comments.

Comments

1

Typically, whatever class is responsible for allocating the object is considered the object's owner, and is therefore responsible for deallocating the instance. The Memory Management Programming Guide gives a good description of this, particularly in the "Object Ownership and Disposal" section

Comments

1

May be this will make you more easy to understand.

UIBarButtonItem * buttonItem = [[UIBarButtonItem alloc] initWithCustomView:customView]
self.bar.variable1 = buttonItem;
[buttonItem release];

Comments

0

YES. unless you are not releasing it in Bar class, you have to release it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.