Search code examples
iosuikituipageviewcontroller

UIPageViewController deallocating first view controller after moving to the third?


I'm using UIPageViewController to display 3 viewcontrollers. If I move to the third and then go back to the first view controller, the first view controller is deallocated from memory. How can I fix this while still using UIPageViewController or is it just not the intended use of UIPageViewController?


Solution

  • Keep a strong reference to the UIViewController's either with an array, or individually in your UIPageViewController. Note that when the device runs low on memory, the controllers will unload their views.

    Swift:

    class PageViewController: UIPageViewController {
        var viewControllers: [UIViewController]?
        // or
        var viewControllerA: UIViewController?
        var viewControllerB: UIViewController?
        var viewControllerC: UIViewController?
    }
    

    Objective-C:

    @interface PageViewController: UIPageViewController
    
    @property (nonatomic, strong) NSMutableArray* viewControllers;
    // or
    @property (nonatomic, strong) UIViewController* viewControllerA;
    @property (nonatomic, strong) UIViewController* viewControllerB;
    @property (nonatomic, strong) UIViewController* viewControllerC;
    
    @end