【问题标题】:Is it ok to allocate a UIView twice and am I releasing it properly?可以两次分配 UIView 并且我是否正确释放它?
【发布时间】:2011-05-05 20:07:12
【问题描述】:

我希望创建 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];

【问题讨论】:

    标签: iphone objective-c memory-management


    【解决方案1】:

    您需要在重新分配 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];
    

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

    【讨论】:

    • ARC 还是一样吗?
    • @jeroldov 删除版本,ARC 应该可以正常工作。
    • 我明白了。我有点担心我的 UIViewController 有很多 UIViews 我添加为菜单,在不使用时可能会产生内存泄漏。我猜它是在 ARC 中自动处理的。
    【解决方案2】:

    此外,如果您创建的所有视图都具有相同的框架,您可能会在循环中执行相同的操作:

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

    只需将 kViewCount 设置为您需要创建的视图数

    【讨论】:

    • 感谢您的建议,但这很明显 :) 另一方面,内存管理并不总是那么简单。
    • 哦,对不起,我只是不知道你的背景是什么)
    猜你喜欢
    • 1970-01-01
    • 2011-04-30
    • 1970-01-01
    • 2022-01-22
    • 2011-05-07
    • 1970-01-01
    • 1970-01-01
    • 2020-09-23
    • 1970-01-01
    相关资源
    最近更新 更多