UIImage *img = [[UIImage alloc] initWithContentsOfFile:@"xx.jpg"]
UIImage *img = [UIImage imageNamed:@"xx.jpg"]
在第二种类型中,图像会被缓存吗? 而在第一种类型中,图像不会被缓存?
答案 0 :(得分:28)
-initWithContentsOfFile:
创建一个没有缓存的新图像,这是一种普通的初始化方法。
+imageNamed:
方法使用缓存。以下是UIImage Reference的文档:
此方法在系统缓存中查找具有指定名称的图像对象,并返回该对象(如果存在)。如果匹配的图像对象尚未在缓存中,则此方法从指定的文件加载图像数据,对其进行缓存,然后返回结果对象。
UIImage将保留已加载的图像,使其保持活动状态,直到低内存条件将导致缓存被清除。
Swift更新:
在Swift中,UIImage(named: "...")
函数是缓存图像的函数。
答案 1 :(得分:9)
只是想留下这个来帮助处理路径名问题。这是一种可以放在UIImage
类别上的方法。
+(UIImage *)imageNamed:(NSString *)name cache:(BOOL)cache {
if (cache)
return [UIImage imageNamed:name];
name = [[NSBundle mainBundle] pathForResource:[name stringByDeletingPathExtension] ofType:[name pathExtension]];
UIImage *retVal = [[UIImage alloc] initWithContentsOfFile:name];
return retVal;
}
如果您没有简单的方法切换到缓存,您可能最终只使用`imageNamed。在大多数情况下,这是一个很大的错误。请参阅this great answer for more details(并同时回答问题和答案!)。
答案 2 :(得分:1)
@ Dan Rosenstark 快速回答..
extension UIImage {
static func imageNamed(name: String, cache: Bool) -> UIImage? {
if (cache) {
return UIImage(named: name)
}
// Using NSString for stringByDeletingPathExtension
let fullName = NSString(string: name)
let fileName = fullName.stringByDeletingPathExtension
let ext = fullName.pathExtension
let resourcePath = NSBundle.mainBundle().pathForResource(fileName, ofType: ext)
if let path = resourcePath {
return UIImage(contentsOfFile: path)
}
return nil
}
}
答案 3 :(得分:0)
正确,缓存第二项。