- (void)viewDidLoad
{
[super viewDidLoad];
[self setNavTitle:@"安全中心"];
UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 49, 320, 413+(iPhone5?88:0))];
[bgImageView setImage:[UIImage imageNamed:iPhone5?@"single_bg_i5.png":@"single_bg.png"]];
[self.view addSubview:bgImageView];
[bgImageView release];
......
}
之前比较疑惑下面这段代码,不知道为什么bgImageView这个变量release之后为甚么还可以使用。现在发现我把c++的思想错误的带入了进来。
添加几段内存引用计数代码:
- (void)viewDidLoad
{
[super viewDidLoad];
[self setNavTitle:@"安全中心"];
UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 49, 320, 413+(iPhone5?88:0))];
[bgImageView setImage:[UIImage imageNamed:iPhone5?@"single_bg_i5.png":@"single_bg.png"]];
NSLog(@"内存计数:%ld", [bgImageView retainCount]);
[self.view addSubview:bgImageView];
NSLog(@"内存计数:%ld", [bgImageView retainCount]);
[bgImageView release];
NSLog(@"内存计数:%ld", [bgImageView retainCount]);
......
}
在输出窗得到以下结果:
2015-11-02 14:35:36.260 ClientV2[16904:178273] 内存计数:1
2015-11-02 14:35:37.779 ClientV2[16904:178273] 内存计数:2
2015-11-02 14:35:37.779 ClientV2[16904:178273] 内存计数:1
我们发现变量release之后的内存计数并不是0,而是1!
这是因为addSubView函数将bgImageView变量的内存引用计数加了1。