开发者

Is it ok to allocate a UIView twice and am I releasing it properly?

I wish to create multiple instances of UIView so i figured instead of creating new variables i'd allocate one UIView and then reallocate it again to create another UIView. Is th开发者_C百科is ok? Plus am I releasing the view properly or is the retain count of tempview is 2 after 2 allocations and a release just brings the retain count to 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];


You need to release tempView before you re-assign it or else it will leak.

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];

Alternately, you could autorelease tempView each time you alloc/init it, but it's better to release when you can and only use autorelease when you have to.


also, if all views you create have the same frame you might do the same in a loop:

const int kViewCount = 8;

NSMutableArray * array = [[NSMutableArray alloc] initWithCapacity:kViewCount];

for(int i = 0; i < kViewCount; ++i)
{
    UIView *tempview = [[UIView alloc] initWithFrame:CGRectMake(15, 30, 320, 460)];
    [array addObject:tempView];
    [tempView release];
}

just set kViewCount to the number of views you need to create

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜