Objective C - 使用ARC分配和删除View Controller的正确方法

时间:2013-11-03 22:24:10

标签: objective-c uiviewcontroller automatic-ref-counting allocation

让我们说我有一个弹出窗口。点击按钮时,必须分配并显示弹出窗口。当调用关闭按钮委托时,必须关闭并正确删除它。我不认为我出于某种原因这样做是正确的:

在.h文件中:

@interface MainViewControoler : UIViewController
{
PopupViewController*            popupView;     
}

@property (retain, nonatomic) PopupViewController* popupView;
@end

在.m文件中:

..
-(void)openButtonPressed
{
  if (!popupView)
  {  
    popupView = [[PopupViewController alloc] init];
    popupView.delegate = self;
  }
  [self.view addSubview:popupView.view];
  popupView.view.frame = self.view.frame;
}

..
-(void)closePopup
{
  [popupView.view removeFromSuperview];
}

我不希望这有任何泄漏,如果弹出窗口打开和关闭1000次,它不会崩溃....这是正确的方法吗?

1 个答案:

答案 0 :(得分:1)

您的代码不会产生泄漏,因为您要分配一次popover。但是,您不需要手动创建实例变量,或者将popover属性设置为nil,ARC将负责此操作,除非您想在释放VC之前解除分配弹出窗口。

请确保您没有多次将弹出窗口视图添加到父视图中(即在调用openButtonPressed之前不再调用closePopup

·H:

@interface MainViewControoler : UIViewController

@property (nonatomic) PopupViewController *popupView;

@end

的.m:

-(void)openButtonPressed
{
  if (!_popupView)
  {  
    _popupView = [[PopupViewController alloc] init];
    _popupView.delegate = self;
  }
  [self.view addSubview:_popupView.view];
  _popupView.view.frame = self.view.frame;
}

-(void)closePopup
{
  [_popupView.view removeFromSuperview];
}