视图控制器中的背景图像导致内存增加+;uicolorWithPatternImage

视图控制器中的背景图像导致内存增加+;uicolorWithPatternImage,image,memory,background,memory-leaks,uicolor,Image,Memory,Background,Memory Leaks,Uicolor,我尝试了两种为视图控制器创建背景图像的方法 我以前对此进行过研究,并得出结论,要进行良好的记忆练习,您应该使用以下方法: NSString *path = [[NSBundle mainBundle] pathForResource:@"controllerBackground" ofType:@"png" inDirectory:@""]; [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageW

我尝试了两种为视图控制器创建背景图像的方法

我以前对此进行过研究,并得出结论,要进行良好的记忆练习,您应该使用以下方法:

NSString *path = [[NSBundle mainBundle] pathForResource:@"controllerBackground" ofType:@"png" inDirectory:@""];

[self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:path]]];
使用其他方法时:

[self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"controllerBackground.png"]]];
这不如使用imageWithContentsOfFile:path方法有效

然而,当使用性能工具“泄漏”监视器测试这两种方法时,我发现发生了一件非常不寻常的事情

使用
imageWithContentsOfFile:path
方法时,问题是在导航控制器内来回加载视图控制器时,每次加载视图控制器时,内存将在大约1mb的范围内不断增加


这个问题也只在新的iOS 4.1和4中出现。在iOS 3.0或3.2中似乎不会出现这种情况。

艾伦,我遇到了同样的问题,发现colorWithPatternImage和initWithPatternImage占用的内存比预期的大。这里有一个链接解释了这一点


对于背景图像,最好避免使用这两种方法

这是一个对我有效的解决方案

UImage *image = [UIImage imageNamed:@"name.png"];
self.view.layer.contents = (id) image.CGImage;

您必须导入QuartzCore,现在我没有每次访问该视图时都会增加2MB内存。

我对此非常陌生-我应该将此代码放在哪里?在ViewController.h文件中?或者,m?这些文件中的代码放在哪里?我在任何地方都试过,但总是出错。除非我弄错了,否则这不会创建模式,只需将您的图像设置为视图的背景。@Alfo当然在.m文件中。我是在viewController的viewDidLoad方法中完成的。关于错误,您是否添加了QuartzCore框架并将其添加到类中?colorWithPatternImage需要大量内存,因为它必须将图像加载到RAM中。UIImageView不这样做,而是将其添加到纹理内存中。colorWithPatternImage旨在与要重复的小图像(如10x10px)一起使用,为此,它做得非常好。