2013-03-01 56 views
1

我對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

回答

2
- (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]; 
1

在你原來的例子,

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