Reputation: 812
I have always found this confusing. Can someone please explain it for me?
In a view controller class, I have, for example, a scroll view and I want to add a number of views to it. So I create, within the view controller, a helper method that creates the view and returns it to the caller. The caller in turn adds this new view to the scroll view.
So here I call the method to get a view and pass it directly to addSubView:
[scrollView addSubView:[self getView]];
And here is the method that creates the view:
-(UIView *)getView {
UIView *v = [[UIView alloc] init];
// do all the guff I need to configure the view
return v;
}
The question is where or when does v
get released? Should I be assigning it as autorelease
when it is created in getView
or do I release it after i have called addSubView:
? Thanks.
Upvotes: 2
Views: 111
Reputation: 64002
Jacob's conclusion is correct, but his reason is wrong, or at least unclear (and I tried but failed to squeeze this into a comment).
In getSubview:
, you have created an object. You are now the owner*. When the method ends, you must release the object, relinquishing your ownership, or it will leak. The fact that you are returning the object from the method makes no difference to this rule.
In this case, since you want the code which called this method to be able to do something with the object, you use autorelease
, saying "I relinquish my ownership, but don't actually get rid of this object until the calling code has a chance to see whether it wants to make a claim". What happens on the other end (retain, copy, immediate release, anything) is of no concern for the code in getSubview:
. All that method needs to do is worry about the memory that it has ownership of. Doing otherwise, i.e, relying on the fact that the calling code will do something specific with the memory, will lead to bugs.
In slightly more technical terms, the object pointed to by v
must be either released or autoreleased because v
is about to go out of scope at the end of the method. Once a name goes out of scope, you must no longer use that name to refer to an object, and if that name was the only reference you had to the object, you have leaked.
*Note that an object can have multiple owners -- any other object which retain
s it becomes a part-owner.
Upvotes: 0
Reputation: 163228
Since -[UIView addSubview:]
obtains ownership of the passed-in view by sending it a -retain
message, you should be sending the return value of getView
an -autorelease
message:
return [v autorelease];
Upvotes: 2