ARC和ViewControllers

时间:2013-03-01 15:50:21

标签: objective-c memory-management automatic-ref-counting

我对ARC有一点误解。我正在使用以下代码创建一个新的UIViewController:

    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的第一个实例的引用?)。每次点击“关闭”按钮,我该怎么办才能让我的课程被解除分配?我想将locationProfile设置为nil会有效,但这意味着我必须在主类中调用一个方法(包含代码块的方法)。

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

注意: l是自定义类的一个实例,其中包含要在LocationProfileView的{​​{1}}中显示的一些信息。

2 个答案:

答案 0 :(得分:2)

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

我假设关闭按钮的目标是viewcontroller本身

一个强大的指针将保留对象,直到viewController本身被释放,除非你赋予它nil

当一个局部变量超出范围

时,它将被释放

可选地

不使用强指针,你可以这样做

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];

答案 1 :(得分:1)

在原始示例中,

LocationProfile *locationProfile=...

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

当您将其设为强属性时,视图控制器会保留locationProfile:

 @property(nonatomic, strong) LocationProfileView *locationProfile;