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.
Since
-[UIView addSubview:]obtains ownership of the passed-in view by sending it a-retainmessage, you should be sending the return value ofgetViewan-autoreleasemessage: