緩衝圖片
— 或者不緩衝
iOS中從程式bundle中載入UIImage一般有兩種方法。第一種比較常見:imageNamed。第二種方法很少使用:imageWithContentsOfFile
為什麼有兩種方法完成同樣的事情呢?
imageNamed的優點在於可以緩衝已經載入的圖片。蘋果的文檔中有如下說法:
This
method looks in the system caches for an image object with the specified name and returns that object if it exists. If a matching image object is not already in the cache, this method loads the image data from the specified file, caches it, and then returns
the resulting object.
這種方法會在系統緩衝中根據指定的名字尋找圖片,如果找到了就返回。如果沒有在緩衝中找到圖片,該方法會從指定的檔案中載入圖片資料,並將其緩衝起來,然後再把結果返回。
而imageWithContentsOfFile方法只是簡單的載入圖片,並不會將圖片緩衝起來。
這兩個方法的使用方法如下:
- UIImage *img = [UIImage imageNamed:@"myImage"]; // caching
- // or
- UIImage *img = [UIImage imageWithContentsOfFile:@"myImage"]; // no caching
那麼該如何選擇呢?
如果載入一張很大的圖片,並且只使用一次,那麼就不需要緩衝這個圖片。這種情況imageWithContentsOfFile比較合適——系統不會浪費記憶體來緩衝圖片。
然而,如果在程式中經常需要重用的圖片,那麼最好是選擇imageNamed方法。這種方法可以節省出每次都從磁碟載入圖片的時間。