2013-08-22 38 views
1

我有一個問題(與this SO問題有關)。但根本問題與我原先想象的完全不同,我需要將它作爲一個新問題發佈;但我會更新上一個問題以引用此問題 - 如果有人能夠提供幫助。將ViewController傳遞給子視圖,然後再次無法釋放iOS中的VC

我有一個UINavigationController它有vcA作爲rootViewControllervcB然後被推入導航堆棧。 vcB有一個子視圖,它是一個UIView子類(稱之爲BSView),並帶有一些按鈕。我需要有vcB知道當BSView按鈕被竊聽的,所以我實現了一個@protocolBBView.h,如下圖所示:

@protocol BBViewDelegate <NSObject> 
@optional 
-(void)buttonAPressed; 
-(void)buttonBPressed; 
-(void)buttonCPressed; 
@end 

@interface BBView : UIView { 
    id<BBViewDelegate> _delegate; 
    NSString *_title; 
} 
- (id)initWithFrame:(CGRect)frame withTitle:(NSString *)title 
     andDelegate:(id<BBViewDelegate>)delegate; 
@end 

BBView.m init方法是這樣的:

- (id)initWithFrame:(CGRect)frame withTitle:(NSString *)title 
           andDelegate:(id<BBViewDelegate>)delegate 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 

     _delegate = delegate; 
     _title = title; 
    } 
    return self; 
} 

其中delegate將是vcB。而當按下buttonA,這段代碼被觸發:

if(_delegate && [_delegate respondsToSelector:@selector(buttonAPressed)]) { 
    [_delegate buttonAPressed]; 
} 

出現做工精細。所有的方法都按預期調用。 這是問題所在。當我將vcB彈回到vcA時,vcB永遠不會被釋放。如果再次按下vcB,則內存只是循環運行。我可以重複這個循環,直到應用程序爆炸。

當我不初始化BBView與任何委託變量(或nil值),則存儲器vcB釋放上的彈出導航。但是當然,vcB永遠不會意識到按鈕敲擊。

有沒有人有任何想法會發生什麼?我一直在搞這個已經很長時間了,我根本無法弄清楚如何通過vcB作爲對象到BBView,並在導航回彈到vcA時讓它釋放。

任何指針將是最有幫助的。

回答

2

您的delegate指針正在創建一個保留循環。你應該聲明delegate變量爲__weak或作爲weak屬性

+0

哇,這很簡單,正是我所期待的。謝謝! – Brett

+0

另外,感謝張貼在我的另一個問題。我也會在前面的問題中引用這個答案。 – Brett

相關問題