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/