(viewConroller.view removeFromSuperview) Thread:1 EXC_BAD_ACCESS (Code=1, address = 0x6000000008)

前端 未结 2 1735
温柔的废话
温柔的废话 2021-01-26 13:20

(^.^) 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 viewcont

相关标签:
2条回答
  • 2021-01-26 13:52

    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.

    0 讨论(0)
  • 2021-01-26 13:56

    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.

    0 讨论(0)
提交回复
热议问题