閱讀後: Memory management of a view controller in Objective-c整蠱內存管理
和
Does UIView's addSubview really retain the view?
我寫了下面的代碼來切換子視圖:
@synthesize switchableView, viewSelector, currentSubview;
//...
if(switchableView.subviews.count != 0)
[[switchableView.subviews objectAtIndex:0] removeFromSuperview]]
self.currentSubview = (veiwSelector.selectedSegmentIndex == 0) ?
[ViewA new] : [ViewB new];
[switchableView addSubview:currentSubview.view];
//[currentSubview release]; //<---crashes if I uncomment this line
它似乎運行很好,如果我註釋掉這條發行版,但我無法繞過原因。這是我理解的方式會發生什麼,也許有人可以告訴我在哪兒出錯:
所以,讓我們考慮currentView:
一個由「新」的消息得到的alloc-ED - 保留計數=答:1
甲得到由設定器保持 - 保留計數= A:2
A的視圖獲得(假定)保留 - 保留計數= A:2.1
下一次通過...
A的子視圖得到釋放計數= A:2
乙通過 '新的' 消息獲取的alloc-ED - 保留計數= B:1 1,A:1
- ,A::1,A:2
甲得到由setter--乙自動釋放乙1個
B獲得由設定器保持
什麼都沒有擺脫A?
所以我要改變我的代碼,還是我錯了的方式存儲管理工作在這種語言...或兩者 -
你有一個額外] removeFromSuperview – robev 2010-11-02 20:41:07