iPhone - 大多数内存有效的初始化图像方式?

los*_*sit 4 iphone memory-management

我已经读过imageNamed:在尝试初始化图像时很糟糕.但那么最好的方法是什么?我正在使用imageWithContentsOfFile:并在我的资源文件夹中传递图像的路径

[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:imageName ofType:@"jpg"]
Run Code Online (Sandbox Code Playgroud)

这个调用在for循环中进行了大约30次.

现在,当我使用乐器运行我的应用程序时,我发现很多内存被NSString用于上面的操作,我们使用字符串文字(@"jpg")乐器将负责的调用者显示为[NSBundle mainBundle]当我使用字符串文字作为类型时,反过来指向该行.

那么在不使用太多内存的情况下初始化图像的最有效方法是什么?

我把声明改成了

img = [UIImage imageWithContentsOfFile:[bndl pathForResource:fileName ofType:extn]]
Run Code Online (Sandbox Code Playgroud)

这里extn是静态的初始化@"jpg".fileName为for循环的每次迭代不断变化.但即使这样,最大限度地使用NSString也是因为[NSBundle mainBundle]并且[NSBundle pathForResource:OfType:]根据仪器.

Bra*_*son 5

我会避免在循环中使用自动释放的对象.如果Instruments在NSBundle pathForResource:ofType:call上报告大量命中,我会在循环外部进行一些处理.

我建议的实现看起来像这样:

NSString *resourcePath = [[[NSBundle mainBundle] resourcePath] retain];

for (int i = 0; i < 1000; ++i) 
{   
    ...

    NSString *pathForImageFile = [resourcePath stringByAppendingPathComponent:fileName];
    NSData *imageData = [[NSData alloc] initWithContentsOfFile:pathForImageFile];

    UIImage *image = [[UIImage alloc] initWithData:imageData];
    [imageData release];

    ... 

    [image release];
}

[resourcePath release];
Run Code Online (Sandbox Code Playgroud)

你将累积一个自动释放的字符串(pathForImageFile),但这不应该那么糟糕.您可以在循环中创建和释放自动释放池,但我建议每10或100次循环通过最多一次,而不是每次通过.此外,resourcePath上的保留和释放可能是多余的,但我把它放在那里,以防你想在这里的某个地方使用自己的自动释放池.