iOS 正确选择图片加载方式

正确选择图片加载方式可以对内存优化起到很大的做用,常见的图片加载方式有下面三种:

//方法1  
UIImage *imag1 = [UIImage imageNamed:@"image.png"];  
//方法2  
UIImage *image2 = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"image.png" ofType:nil]];  
//方法3  
NSData *imageData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"image.png" ofType:nil]];  
UIImage *image3 = [UIImage imageWithData:imageData];  

第一种方法:imageNamed:

  为何有两种方法完成一样的事情呢?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.缓存

  这种方法会首先在系统缓存中根据指定的名字寻找图片,若是找到了就返回。若是没有在缓存中找到图片,该方法会从指定的文件中加载图片数据,并将其缓存起来,而后再把结果返回。对于同一个图像,系统只会把它Cache到内存一次,这对于图像的重复利用是很是有优点的。例如:你须要在 一个TableView里重复加载一样一个图标,那么用imageNamed加载图像,系统会把那个图标Cache到内存,在Table里每次利用那个图 像的时候,只会把图片指针指向同一块内存。这种状况使用imageNamed加载图像就会变得很是有效。优化

  然而,正是所以使用imageNamed会缓存图片,即将图片的数据放在内存中,iOS的内存很是珍贵而且在内存消耗过大时,会强制释放内存,即会遇到memory warnings。而在iOS系统里面释放图像的内存是一件比较麻烦的事情,有可能会形成内存泄漏。例如:当一 个UIView对象的animationImages是一个装有UIImage对象动态数组NSMutableArray,并进行逐帧动画。当使用imageNamed的方式加载图像到一个动态数组NSMutableArray,这将会颇有可能形成内存泄露。缘由很显然的。动画

第二种方法和第三种方法本质是同样的:imageWithContentsOfFile:和imageWithData: 

imageWithContentsOfFile:仅加载图片,图像数据不会缓存,图像会被系统以数据方式加载到程序。所以对于较大的图片以及使用状况较少时,那就能够用该方法,下降内存消耗。this

下面列举出两种方法的详细用法:.net

NSString *path = [[NSBundle mainBundle] pathForResource:@”icon” ofType:@”png”];  
UIImage *image = [UIImage imageWithContentsOfFile:path];  

以及:指针

NSString *filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:“png”];  
NSData *image = [NSData dataWithContentsOfFile:filePath];  
UIImage *image = [UIImage imageWithData:image]; //or = [UIImage imageWithContentsOfFile:filePath];  

若是加载一张很大的图片,而且只使用一次,那么就不须要缓存这个图片。这种状况imageWithContentsOfFile比较合适,系统不会浪费内存来缓存图片。
然而,若是在程序中常常须要重用的图片,那么最好是选择imageNamed方法。这种方法能够节省出每次都从磁盘加载图片的时间。code

相关文章
相关标签/搜索