Alaa Eldin
Alaa Eldin

Reputation: 2268

Afraid of memory leak when use addsubiew method in iOS

in iPhone: When I add a subview to a view, using [myview addsubview: anotherview.view ] will "my view" retain in memory which may cause a problem when adding a big number of views as subviews.

Upvotes: 0

Views: 106

Answers (2)

Oscar Gomez
Oscar Gomez

Reputation: 18488

Yes addSubView retains the subViews you add, and yes if you add way too many subViews you could run into memory issues, but that is highly unlikely, if that happens you will receive the

- (void)didReceiveMemoryWarning

Followed by the:

- (void)viewWillUnload

and then:

- (void)viewDidUnload

This will unload your view, and release its subviews. However don't forget to set the additional subViews to nil on the viewDidUnload method, as that subviews are also retained by the ViewController itself, therefore they will not get released when the view unloads, unless you set them to nil here.

Upvotes: 1

Martin Ullrich
Martin Ullrich

Reputation: 100581

in your example, myview will retain anotherview.view (view.view?..).
However, myview will not be retained as long as you don't add it as a subview to another view or retain it in any other way.

Upvotes: 1

Related Questions