iOS-UIImage imageWithContentsOfFile 和 imageName 对照

1.imageWithContentsOfFile

NSString *imagePath = [NSString stringWithFormat:@"%@/%@",[[NSBundle mainBundle] resourcePath],@"icon.png"];
        UIImage *imageI = [UIImage imageWithContentsOfFile:imagePath];

imageWithContentsOfFile的方式,在使用完毕之后系统会释放。不会缓存下来,所以也就没有这样的问题。一般也不会把全部的图片都会缓存。有些图片在应用中仅仅使用一两次的,就能够用这样的方式。比方新手引导界面的图片等等,就适合这样的方式。

没有明显的界限。

2.imageName

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

imageName的方式会在使用的时候系统会cache,程序猿是无法处理cache,这是由系统自己主动处理的。对于反复载入的图像,速度会提升非常多,这样反而用户体验好。所以假设某张图片须要在应用中使用多次,或者反复引用。使用imageName的方式会更好,
所以,在app中一些常常会使用的,须要反复载入的,使用imageName会提升用户体验!

Apple的官方文档:

imageNamed: 这种方法用一个指定的名字在系统缓存中查找并返回一个图片对象假设它存在的话。假设缓存中没有找到对应的图片,这种方法从指定的文档中载入然后缓存并返回这个对象。

因此imageNamed的长处是当载入时会缓存图片。所以当图片会频繁的使用时,那么用imageNamed的方法会比較好。比如:你须要在 一个TableView里的TableViewCell里都载入相同一个图标,那么用imageNamed载入图像效率非常高。

系统会把那个图标Cache到内存,在TableViewCell里每次利用那个图 像的时候,仅仅会把图片指针指向同一块内存。正是因此使用imageNamed会缓存图片。即将图片的数据放在内存中,iOS的内存非常珍贵并且在内存消耗过大时。会强制释放内存,即会遇到memory warnings。而在iOS系统里面释放图像的内存是一件比較麻烦的事情。有可能会造成内存泄漏。比如:当一 个UIView对象的animationImages是一个装有UIImage对象动态数组NSMutableArray,并进行逐帧动画。当使用imageNamed的方式载入图像到一个动态数组NSMutableArray,这将会非常有可能造成内存泄露。

原因非常显然的。

imageWithContentsOfFile:仅载入图片。图像数据不会缓存。因此对于较大的图片以及使用情况较少时,那就能够用该方法,降低内存消耗。

一、载入图片问题
UIImage image = [UIImage imageNamed:imageFileName];

这样的图片载入方式带有图片缓存的功能。使用这样的方式载入图片后。图片会自己主动添加系统缓存中。并不会马上释放到内存。一些资源使程序中常常使用的图片资源。

使用这样的方式会加快程序的执行降低IO操作,但对于项目中仅仅用到一次的图片。假设採用这样的方案载入。会增导致程序的内存使用添加。

下面为官方对此方法的解释说明:

imageNamed:

Returns the image object associated with the specified filename.

  • (UIImage )imageNamed:( NSString ) name
    Parameters

name
The name of the file. If this is the first time the image is being loaded, the method looks for an image with the specified name in the application’s main bundle.

Return Value

The image object for the specified file, or nil if the method could not find the specified image.

Discussion

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.

二、非缓存的载入方式
+ (UIImage )imageWithContentsOfFile:(NSString )path

  • (UIImage )imageWithData:(NSData )data

三、何时使用imageNamed方法

1、採用imageNamed方法的图片载入情况

图片资源反复使用到,如button背景图片的蓝色背景。这些图片要常常常使用到,并且占用内存少

2、不应该採用的情况:

(1)图片一般仅仅使用一次。如一些用户的照片资源

(2)图片资源较大,载入到内存后,比較耗费内存资源

原文地址:https://www.cnblogs.com/clnchanpin/p/7059085.html