ARC和ViewControllers

问题描述:

我对ARC有点误解。我使用下面的代码创建一个新的UIViewController:ARC和ViewControllers

CGRect screenRect = [[UIScreen mainScreen] bounds]; 

    LocationProfileView *locationProfile = [[LocationProfileView alloc] initWithLocation:l]; 

    locationProfile.view.frame = CGRectMake(0, screenRect.size.height, screenRect.size.width, 400); 
    [appDelegate.window addSubview:locationProfile.view]; 

    [UIView animateWithDuration:.25 animations:^{ 
     locationProfile.view.frame = CGRectMake(0, 0, screenRect.size.width, screenRect.size.height); 
    }]; 

在它的UIView我把一个按钮,用于去除屏幕视图。这个问题是,locationProfile被添加到屏幕后立即被释放,所以每次我试图点击“关闭”按钮(这将调用LocationProfileView类中的方法),我的应用程序将崩溃。

所以我增加了一个属性:

@property(nonatomic, strong) LocationProfileView *locationProfile; 

,改变代码的第二行:

locationProfile = [[LocationProfileView alloc] initWithLocation:l]; 

,但现在我的课不会被释放,直到我再次启动它(因为它失去对LocationProfileView的第一个实例的引用?)。每次点击“关闭”按钮时,我应该怎么做才能让我的课程被释放?我想设置locationProfilenil会工作,但这意味着我将不得不在主类(包含代码块)中调用一个方法。

这样做的正确方法是什么?对不起,如果我的问题太不理智。

注: l是其中包含了一些相关信息将显示在LocationProfileViewUIVIew自定义类的一个实例。

+0

哪里'UIViewController'你提到? – Richard 2013-03-01 17:00:41

- (void)closeButtonCallBack { 
    [self.locationProfile removeFromSuperview]; 
    self.locationProfile = nil; 
} 

我假设你的关闭按钮的对象是视图控制器本身

很强的指针保留对象,直到viewController本身被释放,除非你指定它为零

一个局部变量将在释放时释放超出范围

或者

不使用强指针,你可以做到这一点

LocationProfileView *locationProfile = [[LocationProfileView alloc] initWithLocation:l]; 

UIButton *close = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
close.frame = CGRectMake(0, 100, 100, 30); 
[close addTarget:locationProfile action:@selector(removeFromSuperview) forControlEvents:UIControlEventTouchUpInside]; 
[self.view addSubview:close]; 

在你原来的例子,

LocationProfile *locationProfile=... 

是一个局部变量。所以一旦你从构造函数返回它就会被释放。这就是你观察到的。

当你让一个强大的属性,视图控制器保留locationProfile:

@property(nonatomic, strong) LocationProfileView *locationProfile; 
+0

它不一定会在构造函数后被释放,但肯定当函数的堆栈帧被压碎时。 – CodaFi 2013-03-01 16:40:28

+0

对不起,但这是错误的。您无需在ARC下明确发布保留的属性,并且将本地ivar设置为零也不会释放它。 – ChrisH 2013-03-01 16:58:31

+0

@ChrisH“本地伊娃”没有意义;你想说什么? – Richard 2013-03-01 17:02:58