方法removeFromSuperView如何工作? 我的記憶問題不好訪問時,我想重新初始化視圖內存管理
- (id)init {
if (!(self = [super init]))
return nil;
_mainView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
NSLog(@"retainCount :%d", [_mainView retainCount]);
UIButton *reInitButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0f,0.0f,90.0f,35.0f)];
[reInitButton addTarget:self action:@selector(buttonDidTapped:) forControlEvents:UIControlEventTouchUpInside];
[[self view] addSubView:_mainView];
NSLog(@"retainCount :%d", [_mainView retainCount]);
[_mainView release];
NSLog(@"retainCount :%d", [_mainView retainCount]);
return self;
}
- (void)buttonDidTapped:(id)sender {
[_mainView removeFromSuperView]; //crash during second times press the button
NSLog(@"retainCount :%d", [_mainView retainCount]);
_mainView = [[UIView alloc] initWithFrame[[UIScreen mainScreen] bounds]];
[[self view] addSubView:_mainView];
NSLog(@"retainCount :%d", [_mainView retainCount]);
[_mainView release];
NSLog(@"retainCount :%d", [_mainView retainCount]);
}
我的NSLog每一個時代有任何保留或頁頭或釋放關鍵字。結果非常奇怪。
//init
retainCount : 1
retainCount : 2
retainCount : 1
//1st time pressed button
retainCount : 1 //remove super view didn't decrease
retainCount : 2
retainCount : 1
//2nd time pressed button
retainCount : 0 //crash. Memory bad access
奇怪的是它爲什麼沒有在第一次按下時崩潰?
+1在這種情況下設置爲零。 – 2011-05-15 05:33:51
請注意,將release釋放到'dealloc',並且仍然在按鈕的動作中創建新視圖將導致泄漏。 – 2011-05-15 05:42:45
@Josh Caswell - 是的,的確如此。這是'nil'事情派上用場的地方...... if(_mainView)[_mainView release]; _mainView =/* ... * /;'但是你仍然希望在dealloc中有一個版本。 – asveikau 2011-05-15 05:45:33