简体   繁体   中英

“message sent to deallocated instance” - Can't find a way to retain.

I have a scroll view with paging control. It loads several pages according to an array, and each page has its table view.

   for(id name in categories) {

        NSLog(@"Loading Page.%i",i);
        NSLog(@"categories count:%i",[categories count]);

       TasksPageViewController *tasks = [[TasksPageViewController alloc] init] ;

       tasks = [self.storyboard instantiateViewControllerWithIdentifier:@"TasksPageViewController"];

        CGRect frame = scrollView.frame;
        frame.origin.x = frame.size.width * i;
        frame.origin.y = 0;
        tasks.view.frame = frame;

        [tasks populateWithData:(i-1) categoryName:name];

        [self.scrollView addSubview:tasks.view];

        i++;

    }

the .h file is:

#import <UIKit/UIKit.h>
#import "MainPageViewController.h"
#import "TasksPageViewController.h"

@interface ViewController : UIViewController{

    UIScrollView *scrollView;
    IBOutlet UIPageControl *pageControl;

    // To be used when scrolls originate from the UIPageControl
    BOOL pageControlUsed;
}

@property (nonatomic, strong) IBOutlet UIScrollView *scrollView;
@property (nonatomic, strong) IBOutlet UIPageControl *pageControl;

- (void)scrollViewDidScroll:(UIScrollView *)scrollView;
- (IBAction)changePage;

@end

The UITableView though is returning

*** -[TasksPageViewController tableView:numberOfRowsInSection:]: message sent to deallocated instance 0x68efac0

(originally it was a EXEC_BAD_ACCESS , but got this with NSZombiesEnabled)

I don't know how to proceed, I think I have to retain the tasks but how?

When adding the view of a view controller as a subview of a view you control, you need to retain the controller. keep it as a property with retain/strong, or an array of view controllers if there are many of them

in this case adding the view as a subview has retained it, so you still have a reference to the table view. but the view controller has been dealloc'd which is why the datasource (which is the view controller for UITableViewController) method is being sent to a deallocated instance

Also, why do you initialise the view controller, and then immediately instantiate it from the storyboard?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM