是否可以分配UIView两次,我是否正确释放它?

Tob*_*ias 0 iphone memory-management objective-c

我希望创建UIView的多个实例,所以我想而不是创建新变量我会分配一个UIView,然后再次重新分配它以创建另一个UIView.这个可以吗?我是否正确地发布了视图,或者在2次分配后,tempview的保留计数是2还是释放只会使保留计数为1?

NSMutableArray *array = [[NSMutableArray alloc] init];  

UIView *tempview = [[UIView alloc] initWithFrame:CGRectMake(15, 30, 320, 460)];

[array addObject:tempView];

tempview = [[UIView alloc] initWithFrame:CGRectMake(15, 30, 320, 460)];

[array addObject:tempView];

[tempview release];

[array release];
Run Code Online (Sandbox Code Playgroud)

Ter*_*cox 6

您需要在重新分配之前释放tempView,否则它将泄漏.

NSMutableArray *array = [[NSMutableArray alloc] init];  
UIView *tempview = [[UIView alloc] initWithFrame:CGRectMake(15, 30, 320, 460)];
[array addObject:tempView];
[tempView release]; //you need this to avoid leaking at the next line

tempview = [[UIView alloc] initWithFrame:CGRectMake(15, 30, 320, 460)];
[array addObject:tempView];
[tempview release];
[array release];
Run Code Online (Sandbox Code Playgroud)

或者,您可以在每次分配/初始化时自动释放tempView,但最好在可以时释放,并且在必要时仅使用自动释放.