天天看點

關于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];

}

以後會陸續寫一些文章,希望和大家一起進步~