读书人

内存泄漏有关问题

发布时间: 2012-03-31 13:13:26 作者: rapoo

内存泄漏问题
有如下代码
headerViewArray = [[NSMutableArray alloc] init];
UIView* customView;

customView = [[UIView alloc] initWithFrame:CGRectMake(0,0,300,40)];
[headerViewArray addObject:customView];
customView = [[UIView alloc] initWithFrame:CGRectMake(0,0,300,40)];
[headerViewArray addObject:customView];
customView = [[UIView alloc] initWithFrame:CGRectMake(0,0,300,40)];
[headerViewArray addObject:customView];
customView = [[UIView alloc] initWithFrame:CGRectMake(0,0,300,40)];
[headerViewArray addObject:customView];

在dealloc函数中有:
[headerViewArray release];

问:上述customView = [[UIView alloc] initWithFrame:CGRectMake(0,0,300,40)]; 是否产生了内存泄漏
是否需要调用
[customView release];
也就是变成如下:
headerViewArray = [[NSMutableArray alloc] init];
UIView* customView;

customView = [[UIView alloc] initWithFrame:CGRectMake(0,0,300,40)];
[headerViewArray addObject:customView];
[customView release];
customView = [[UIView alloc] initWithFrame:CGRectMake(0,0,300,40)];
[headerViewArray addObject:customView];
[customView release];
customView = [[UIView alloc] initWithFrame:CGRectMake(0,0,300,40)];
[headerViewArray addObject:customView];
[customView release];
customView = [[UIView alloc] initWithFrame:CGRectMake(0,0,300,40)];
[headerViewArray addObject:customView];
[customView release];
才不会产生内存泄漏

[解决办法]
需要调用
[customView release];
[解决办法]
你可以:
customView = [[[UIView alloc] initWithFrame:CGRectMake(0,0,300,40)] autorelease];

也可以:
customView = [[UIView alloc] initWithFrame:CGRectMake(0,0,300,40)];
[headerViewArray addObject:customView];
[customView release];

读书人网 >Iphone

热点推荐