Releasing subviews
I'm fairly new at programming for iOS, and I am experiencing a problem with an iPa开发者_开发技巧d app I'm developing. I am using a splitview controller to add a subview to the splitview's detailview every time a cell in the splitview's rootview is tapped. This is fine until the stack gets too high and I run out of memory. How can I release the previous subview after the new view is added to the stack? Or is there a better way of solving this problem?
Thanks
To remove a view from its superview:
[view removeFromSuperview];
The superview will release the view at that point. So if the superview is the only actor with an owning reference then the view will be deallocated. To put it another way, this:
[superview addSubview:view];
causes superview to retain view. So you often see blocks of code like:
view = [[ViewClass alloc] initWithFrame:frame]; // I own view
[superview addSubview:view]; // superview and I both own view
[view release]; // now only superview owns view;
// it'll be deallocated if
// superview ever relinquishes
// ownership
So you now have a pointer to view that is valid for as long as the view remains in the superview. So it's subsequently safe to post removeFromSuperview
to it, but after that use of view is explicitly unsafe. The view object will live only between the alloc/init and the removeFromSuperview. It'll be deallocated upon being removed.
Per normal Cocoa reference counting rules, the following is pretty much the same as a drop-in replacement for an alloc/init and a subsequent release:
view = [ViewClass viewWithFrame:frame]; // view is an autoreleased object;
// the autorelease pool owns it
[superview addSubview:view]; // superview now owns view also
// the autorelease pool will relinquish ownership automatically, in the future...
If you haven't done anything manually to affect behaviour, being just in the normal runloop, then things in the autorelease pool are safe for the life of the current call stack. In this case you'd treat view exactly as you did in the manual alloc/init example, possibly having made the change just to save a line of code and leave memory management implicit.
精彩评论