ios - 移除对象时内存未释放 - 不清楚在 ARC 中释放的正确方法

标签 ios objective-c

Xcode 5,iOS7

我有一个应用程序可以在循环中创建 UILabel,并在数组中引用它们。
在反复调用“创建”方法后,我注意到我的内存使用量增加了。
我想清除数组和相关的 UILabel 对象以释放内存,
因为它似乎没有发生在我当前的代码中。相反,每次通过我的循环
我可以看到我的内存使用量在增加并且从未减少。我目前正在使用 Storyboards 和 ARC。

我怎样才能正确释放 UILabel,因为 ARC 似乎没有为我做这件事?

@implementation myViewController
CGPoint tmpPoint;
NSMutableArray *allDots;
/// more code here
//
// This method is called repeatedly from another loop
-(void)createLabels{
//remove any previous labels
//I'm pretty sure this is not actually clearing the UILabels but rather the pointer to the labels?
    for(short i=0; i<10; i++){
        UILabel *junkDot=[allDots objectAtIndex:i];
        junkDot=nil;
    }
// Either of these statements should clear the references/pointers
//        [allDots removeAllObjects];
    allDots=[[NSMutableArray alloc] init];

//create a new group of labels
    for(short i=0; i<10; i++){
        // code to generate Point values
        [self makeLabel:tmpPoint];
    }
}

-(UILabel*)makeLabel:(CGPoint)thePoint{
    CGRect xFrame=CGRectMake(thePoint.x, thePoint.y, 40, 20);
    UILabel *tmpLabel=[[UILabel alloc] initWithFrame:xFrame];

    [self.view addSubview:tmpLabel];

    [allDots addObject:tmpLabel];

    return tmpLabel;
}

最佳答案

您需要阅读内存管理的基础知识。

在 ARC 中,只要至少有一个对它们的强引用,对象就会保存在内存中。一旦不再有对对象的任何强引用,它就可以被释放。

NSArray(或 NSMutableArray)保持对添加到它的任何对象的强引用。如果你从一个可变数组中移除一个对象(例如使用 removeObjectAtIndex: ),数组就会释放它的强引用。

您从数组中获取对象然后将局部变量设置为 nil 的代码除了浪费时间之外什么也没做:

for(short i=0; i<10; i++){
    UILabel *junkDot=[allDots objectAtIndex:i];
    junkDot=nil;
}

当您使用 addSubview: 将 View 对象添加到 View 层次结构时,superview也保持对对象的强引用。

因此,如果您创建一堆标签并将它们都放在一个数组中并将它们添加为内容 View 的 subview ,则每个标签都有 2 个强引用。标签在从其父 View 中删除并从数组中删除之前不会被释放。

关于ios - 移除对象时内存未释放 - 不清楚在 ARC 中释放的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24477167/

相关文章:

ios - iOS 9 之前的 Xamarin UIStackView

ios - 带有相机 View 的程序化屏幕截图

ios - NSMutableArray 数据按距离排序

ios - 无法添加带有 url 的源

ios - 如何在 tableView (Swift) 中删除行后立即选择另一行

ios - 为什么/如何controllerDidChangeContent 工作?

ios - 自定义警报 View 的验证

iphone - 过滤输入到 UITextField 中的字符

ios - 弹出 View Controller ,然后同时关闭前一个 View Controller

iphone - 如何将(动画)UICollectionView 单元格移入和移出圆形 [PICS]