PageViewController: How to release ViewControllers

2019-02-15 02:57发布

I have a problem with the new PageViewController (the one with the nifty page turn animations). As far as I understand, there is a stack of ViewControllers which you need to set up like so:

PageView *startingViewController = [self.modelController viewControllerAtIndex:0];
NSArray *viewControllers = [NSArray arrayWithObject:startingViewController];
[self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:NULL];

So far so good. Then you need to set up a source (your model Controller). In your model controller, you need to have four methods:

-(PageView *)viewControllerAtIndex:(NSUInteger)index
-(NSUInteger)indexOfViewController:(PageView *)viewController
-(UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController
-(UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController

The last two are called if you turn the page (to the next or the previous). The second one simply determines the page index number. The interesting one - and the one where my problem is - is the first one. The first one returns a ViewController (which in my example is called PageView). This is the very end of the method:

PageView *pView = [[PageView alloc] init];
return pView;

I am wondering where this pView ends up and how I can release it? I guess autorelease is a bad idea as I don't know how long it is needed. If it ends up in the stack (which I guess it does), how long is it needed? Surely just for the next couple of pages. For instance, imagine setting up a pView for page 1. You then turn to page 2 and 3. By then you don't need page 1 anymore - you could release it. If you go back to page 1 it will be reloaded.

I put log commands in my pView dealloc, but it is never called. So I guess I'm leaking every single viewControllers I've created.

Any ideas how and where to release them once they are not needed anymore?

1条回答
家丑人穷心不美
2楼-- · 2019-02-15 03:33

autorelease is exactly what you need. This is the perfect situation for which autorelease was designed i.e. you need to return an object but don't know how long it will be needed.

PageView *pView = [[PageView alloc] init] autorelease];
return pView;

Your PageView instance is allocated on the heap (not the stack) and PageViewController will take ownership of it and retain it if it needs to keep it around. It becomes PageViewController's responsibility after your method has returned.

(Otherwise just use ARC and let the compiler take care of it)

查看更多
登录 后发表回答