(viewConroller.view removeFromSuperview) Thread:1

2020-05-09 07:53发布

问题:

(^.^) Hi sorry for my English is not good.

Hi I have the next issue I create 2 buttons the first one button create one view controller and add his view to other viewcontroller the second button I release the view controller created and remove the view from the parent. If I tap faster the 2 buttons crash with the message like in the post Title this is the code

(I now this is because memory problems but what is the problem?? I do this only for see the memory managment with XCODE-PROFIL-INSTRUMENTS-Allocations please Help):

- (IBAction)create:(id)sender{
       vc = nil;
       vc = [[[VC alloc] initWithNibName:@"VC" bundle:[NSBundle mainBundle]] retain];
      [_VW addSubview:vc.view];
}

And kill with this button:

- (IBAction)kill:(id)sender{
      [vc.view removeFromSuperview];
      [vc release];
}

回答1:

When you press the button fast, at least in the kill button's case, it attempts to release the view however many times you press the button (assuming the code works when you press the button only once). The EXC_BAD_ACCESS code means you are trying to access some memory location that has already been released.

The best way to protect against this would be to use the [NSButton setEnabled:(BOOL)enabled] method. When the create button is pressed, enable the kill button and disable the create button. When the kill button is pressed, disable the kill button and enable the create button. This will prevent accidental extra allocations or releases.

Also, in your create method, you should remove that extra retain in vc's allocation line. alloc automatically increments the retain count (to 1), and that extra retain is bringing it up to 2. With the way it is, when the kill button is pressed, the object is released once, but the retain count is still 1, creating a memory leak.



回答2:

It seems that vc is an iVar, so you should not send release in kill: method. So just remove the code line:

[vc release];

and add it to your dealloc method.


Note, it's better to use the code like below for your create:

if (vc == nil)
  vc = [[[VC alloc] initWithNibName:@"VC" bundle:[NSBundle mainBundle]] retain];
[_VW addSubview:vc.view];

Otherwise, when your vc is not nil, it'll lead a memory leak.