天天看點

imageNamed與imageWithContentsOfFile加載圖檔的差別

//讀取本地圖檔  

#define loadimage(file,ext) [uiimage imagewithcontentsoffile:[[nsbundle mainbundle]pathforresource:file oftype:ext]]  

//定義uiimage對象  

#define image(a) [uiimage imagewithcontentsoffile:[[nsbundle mainbundle] pathforresource:a oftype:nil]]  

#define imagenamed(_pointer) [uiimage imagenamed:_pointer] 

@不推薦第三個的原因:

+ (uiimage *)imagenamed:(nsstring *)name方法

這個方法用一個指定的名字在系統緩存中查找并傳回一個圖檔對象如果它存在的話。如果緩存中沒有找到相應的圖檔,這個方法從指定的文檔中加

載然後緩存并傳回這個對象。是以的優點是當加載時會緩存圖檔。是以當圖檔會頻繁的使用時,那麼用的方法會比較好。但正是是以使用會緩存圖檔,即

将圖檔的資料放在記憶體中,ios的記憶體非常珍貴并且在記憶體消耗過大時,會強制釋放記憶體,即會遇到memory warnings。

為避免這種error,可以使用如下方法:

   imagewithcontentsoffile 僅加載圖檔,圖像資料不會緩存。是以對于較大的圖檔以及使用情況較少時,那就可以用該方法,降低記憶體消耗。 

  nsstring *path = [[nsbundle mainbundle] pathforresource:@" " oftype:@" "];

  uiimage *image = [uiimage imagewithcontentsoffile:path];

當然,對于圖檔處理等相關程式,可以直接為uiimage寫一個catagory,重載imagenamed方法,如下:

@implementation uiimage(imagenamed_hack) 

+(uiimage *)imagenamed:(nsstring *)filename

   // 方法一

   nsstring *filepath = [[nsbundle mainbundle] pathforresource:filename oftype:“png”];  

   nsdata *image = [nsdata datawithcontentsoffile:filepath];  

   uiimage *image = [uiimage imagewithdata:image]; 

   return image;

   // 方法二(特别注意,oftype中填寫的字尾名不需要加".")

   1.return [uiimage imagewithcontentsoffile:[[nsbundle mainbundle]pathforresource:filename oftype:@"png"]];

   2.return [uiimage imagewithcontentsoffile:[nsstring stringwithformat:@"%@/%@", [[nsbundle mainbundle] bundlepath], filename ] ];

@end

1.用imagenamed函數

[uiimage imagenamed:imagename];

2.用nsdata的方式加載,例如:

nsstring *filepath = [[nsbundle mainbundle] pathforresource:filename oftype:extension];

nsdata *image = [nsdata datawithcontentsoffile:filepath];

[uiimage imagewithdata:image];

@由于第一種方式要寫的代碼比較少,可能比較多人利用imagenamed的方式加載圖像。其實這兩種加載方式都有各自的特點。

1)用imagenamed的方式加載時,系統會把圖像cache到記憶體。如果圖像比較大,或者圖像比較多,用這種方式會消耗很大的記憶體,而且釋放圖像的記憶體是一件相對來說比較麻煩的事情。例如:如果利用imagenamed的方式加載圖像到一個動态數組nsmutablearray,然後将将數組賦予一個uiview的對象的animationimages進行逐幀動畫,那麼這将會很有可能造成記憶體洩露。并且釋放圖像所占據的記憶體也不會那麼簡單。但是利用imagenamed加載圖像也有自己的優勢。對于同一個圖像系統隻會把它cache到記憶體一次,這對于圖像的重複利用是非常有優勢的。例如:你需要在一個tableview裡重複加載同樣一個圖示,那麼用imagenamed加載圖像,系統會把那個圖示cache到記憶體,在table裡每次利用那個圖像的時候,隻會把圖檔指針指向同一塊記憶體。這種情況使用imagenamed加載圖像就會變得非常有效。

2)利用nsdata方式加載時,圖像會被系統以資料方式加載到程式。當你不需要重用該圖像,或者你需要将圖像以資料方式存儲到資料庫,又或者你要通過網絡下載下傳一個很大的圖像時,請盡量使用imagewithdata的方式加載圖像。