Search code examples
iospushviewcontrolleraddsubviewsuperviewpoptoviewcontroller

Remove subview on viewdisappear add again when appear - not working- ios sdk


I am working with the application and want to remove table view when view disappear and want to add that same table view when view appear.

Currently

  1. From A ctr(push) -> B ctr

  2. From B ctr(push) -> C ctr -- I removed tableview in B ctr from superview in viewwilldisappear -- works fine.

  3. From C ctr(pop) -> B ctr -- In view will appear of B ctr I added table view again. Viewwillaprea get called but tableview is not added as subview.

4 From B ctr(pop) -> A ctr

  1. From A ctr(push) -> B ctr -- This time in B ctr tableview appears.

It seems like when I come back with popViewControllerAnimated its not adding table as subview.

I have table in xib.

I want to do this in order to release the allocated memory.

tableview outlet

 @property (nonatomic,weak) IBOutlet UITableView *tView;

Remove table view in viewWillDisappear

  [self.tView removeFromSuperview];

Adding back in viewWillAppear

  [self.view addSubview:self.tView];

Thanks in advance


Solution

  • You shouldn't worry about this unless you have reason to - i.e. repeated memory warnings. And, if you do that those you should work out why - it's highly unlikely to be the table view. If anything it may be the data you load to populate the table view, so you could think about removing that data when not on display...

    Anyway, your issue is that you destroy and don't recreate the table view. Your property:

     @property (nonatomic,weak) IBOutlet UITableView *tView;
    

    is weak, so when you remove the view from its superview it is deallocated because nothing else is holding a reference to it.

    When you later call:

     [self.view addSubview:self.tView];
    

    you need to have recreated the table view and added it to the subview before you call self.tView = newTView because otherwise nothing will be retaining it again and it would be destroyed before you get to use it.

    Key points:

    1. fix any memory issue (profile to find the true cause)
    2. don't remove the table view