問題描述
圖片資源放在Assets.xcassets中,分別用UIImage的類方法imageNamed和imageWithContentsOfFile獲取圖片對象,但發生奇怪的情況,前者獲取到圖片對象,后者結果為nil。代碼如下:
1.通過UIImage的類方法imageNamed:可以獲取到圖片對象。
UIImage *imge = [UIImage imageNamed:@"test.jpg"];
2.但通過UIImage的類方法imageWithContentsOfFile:得到img為nil
//NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"jpg"]; NSString *path = [[NSBundle mainBundle] pathForResource:@"test.jpg" ofType:nil]; UIImage *imge = [UIImage imageWithContentsOfFile:path];
問題分析
其實,UIImage創建對象有兩種方法:
- imageNamed:創建的對象會緩存到系統內存中,不會立即釋放到內存。好處是再次加載使用這種方式會減少讀取操作,加快程序運行。缺點:加載過多圖片會占用大量內存空間。
-
- 創建圖片對象,首先在緩存中查找是否有該對象,有則直接取出對象,
- 沒有則從bundle中查找圖片資源,有則創建對象並返回。
- bundle中也沒有圖片資源,則返回nil。
- imageWithContentsOfFile:mageWithContentsOfFile創建的對象不會緩存到系統內存中。好處是不產生緩存。缺點:對於經常使用的小圖片,會頻繁讀取。
imageNamed只需傳文件名,imageWithContentsOfFile需要傳入文件全路徑,而文件全路徑可以通過NSBundle得到。
注意:
如果在項目中的Assets.xcassets(藍色文件夾
)
- 不可以NSBundle獲得資源路徑,然后imageWithContentsOfFile加載
- 可以imageNamed加載
如果在項目中真實文件夾(藍色文件夾,除Assets.xcassets):
- 可以NSBundle獲得資源路徑,然后imageWithContentsOfFile加載。注意要帶文件夾路徑,例如[[NSBundle mainBundle]pathForResource:@"test.jpg" ofType:nil inDirectory:@"image"]
- 不可以imageNamed加載
如果在項目中虛擬文件夾(黃色文件夾):
- 可以NSBundle獲得資源路徑,然后imageWithContentsOfFile加載
- 可以imageNamed加載
問題解決
只能imageNamed獲取Assets.xcassets的圖片資源