UILabel(CALayer)正在使用大量的虚拟内存

Xcode and Instruments我使用大量的虚拟内存(匿名VM)来看UILabel (CALayer) )。 我发现每个UILabel大约有235 KB的虚拟内存。

我认为这可能是iOS 7.1或7.1.1的一个新问题。

这是预期的吗?

我创build了一个简单的程序,创build500 UILabelsInstruments显示使用115MB的内存。 在大约1500个标签上,应用程序被操作系统终止。

 for (int i = 0; i < 500; i++) { index = (int)[self.items count]; index++; frame = CGRectMake(10.0, 20, 300.0, 50.0); UILabel *newLabel = [[UILabel alloc] initWithFrame:frame]; newLabel.text = [NSString stringWithFormat:@"This is text for label: %d", index]; newLabel.backgroundColor = [UIColor whiteColor]; [self.view addSubview:newLabel]; [self.items setObject:newLabel forKey:[NSNumber numberWithInteger:index]]; } 

思考?

UILabel,以及任何使用drawRect的视图(至less在iOS 7+上)都由纹理支持,所以每个UILabel将使用大量的内存,标签越大,使用的内存就越多。

我在You Doodle的照片编辑扩展中发现了这个特别的痛苦,它允许在照片应用中添加文本。 不幸的是,我必须大大限制文本的范围,因为照片扩展在崩溃之前比常规应用更受内存使用限制。

这可以很容易地通过运行仪器和分配一大堆UILabel并设置它们的文本并确保它们全部可见来validation,即:

 CGRect f = CGRectMake(0.0.0f, 0.0f, 300.0f, 300.0f); for (NSInteger i = 0; i < 100; i++) { UILabel* l = [[UILabel alloc] initWithFrame:f]; l.backgroundColor = UIColor.blueColor; l.textColor = UIColor.whiteColor; l.text = @"UILabel text for the memory test"; l.numberOfLines = 0; [self.view addSubview:l]; } 

当报告这种事情(堆栈溢出或苹果),你真的应该消除不必要的多余的代码。 这个代码足以重现这个现象:

 for (int i = 0; i < 500; i++) { CGRect frame = CGRectMake(10.0, 20, 300.0, 50.0); UILabel *newLabel = [[UILabel alloc] initWithFrame:frame]; newLabel.backgroundColor = [UIColor whiteColor]; [self.view addSubview:newLabel]; } 

这导致应用程序在我的机器上使用129MB。 (不需要使用仪器:Xcode现在直接显示内存使用情况。)

我的第一个回应是:“我想我不觉得这个太令人吃惊了,如果将frame改为更小的matrix,则使用更less的内存,视图是昂贵的,它们由位图支持。

但是,如果您将UILabel更改为普通的UIView,则只能使用13MB。 我认为这是一个足够的差异,以保证提出一个错误。

Interesting Posts