天天看点

关于UIImage自动释放问题

在做iPhone和iPad应用中,可能很多人都会用到xib和storyboard。

在写代码时,我们在加载一张图片时,经常会这样写到[UIImage imageNamed:@"text.png"];用于图片的加载。而在xib和storyboard中使用UIImageView控件时,一般会在这里放图片名字。

关于UIImage自动释放问题

但是注意内存的小伙伴就会知道,在这里添加图片名字后,切换场景或者界面时,内存不能及时得到释放。

这是因为使用xib和storyboard的这种方式加载图片其实就是我们代码的imageNamed方法。这个方法在将图片添加到内存缓存中是不能及时释放掉的,加之现在苹果的ARC,所以如果需要经常切换场景或者一个界面中图片元素过多时,采用这种方式显然不是明智的选择。

在苹果UIImage这个类中还有一个方法,+ (UIImage *)imageWithContentsOfFile:(NSString *)path;这种方法加载的方法加载的图片是不会缓存的。得到的对象时autoRelease的,当autoReleasePool释放时才释放。

我自己写了一个方法把它的路径稍微封装了一下。可能不是很完善,在这里和大家分享一下,希望有用得到的人。

+(UIImage *)imageNameWithString:(NSString *)name

{

    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSArray *array = [name componentsSeparatedByString:@"."];

    NSString *path;

    path = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/resources/images"];

    path = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",name]];

    if (![fileManager fileExistsAtPath:path]) {

        //如果沙盒目录没有从工程目录中去找图

        if (array && [array count] > 1) {

            path = [[NSBundle mainBundle] pathForResource:[array objectAtIndex:0] ofType:[array objectAtIndex:1]];

        }else {

            path = [[NSBundle mainBundle] pathForResource:name ofType:@"png"];

        }

    }

    return [UIImage imageWithContentsOfFile:path];

}

以后会陆续写一些文章,希望和大家一起进步~