imageNamed 的优势是什么?

what is the advantage of imageNamed?

我知道加载这样的图片

  UIImage *image = [UIImage imageNamed:@"img"];

将缓存图像并像这样加载它不会

  UIImage *image = [UIImage imageWithContentsOfFile:@"img.png"];

人们说访问缓存图像会更快,因为 iOS 将从内存中访问它,我们不会有读取和解码文件的开销。好的,我明白了,但是假设我使用第二种非缓存方法将图像加载到作为属性的视图上,就像这样

  UIImage *image = [UIImage imageWithContentsOfFile:@"img.png"];
  self.imageView = [[UIImageView alloc] initWithImage:image];

图像不是已经在内存中了吗?如果我想访问它,我只需执行 imageView.image 并从内存中获取它。

我可能累了,但我无法想象缓存版本的单一用途,或者我不明白这个缓存的含义。

想解释一下吗?谢谢。

假设您的图像是您在 7 个不同的视图控制器中使用的某个图标...您可以加载一次图像然后将其传递给每个 VC 或者您可以使用 imageNamed ... 你的选择。

来自the documentation

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 locates and loads the image data from disk or asset catelog, and then returns the resulting object. You can not assume that this method is thread safe.

假设您的应用中有一张图片。当你需要使用图片时,你使用这个代码:

UIImage *image = [UIImage imageWithContentsOfFile:@"img.png"];

iOS 然后会在应用程序包中查找您的图像,将其加载到内存中,然后将其解码为 UIImage。

但是,假设您需要 10 个不同的对象来使用该图像,并且您加载它的方式与此类似:

for (ClassThatNeedsImage *object in objects) {
    object.image = [UIImage imageWithContentsOfFile:@"img.png"];
}

(这不是最好的例子,因为您可以只加载一次图像并将其传递给每个对象。但是,我有更复杂的代码,这不是一个选项。)

iOS 将查找图像 10 次,将其加载到内存中 10 次,然后解码 10 次。但是,如果您使用 imageNamed:

for (ClassThatNeedsImage *object in objects) {
    object.image = [UIImage imageNamed:@"img"];
}

来自 Wikipedia:

In computing, a cache is a component that transparently stores data so that future requests for that data can be served faster.

UIImage使用的缓存存储在内存中,访问速度比磁盘快很多

第一次通过循环,iOS 在缓存中查找图像是否存储在那里。假设你之前没有用 imageNamed 加载这张图片,它找不到它,所以它会查找图片,将它加载到内存中,解码它,然后将它复制到缓存中。

在其他迭代中,iOS 在缓存中查找图像,并将其复制到 UIImage 对象中,因此它根本不需要进行任何硬盘访问。


如果您打算在应用程序的生命周期内只使用一次图像,请使用 imageWithContentsOfFile:。如果要多次使用该图像,请使用 imageNamed:.