ios开发UIImage imageNamed方法的误用

[UIImage imageNamed:@"icon.png"]

用上面的方法加载图片有问题。该方法即可以从bundle中读取图片。

这种方法在application bundle的顶层文件夹寻找由供应的名字的图象 。
如果找到图片,装载到iPhone系统缓存图象。那意味图片是(理论上)放在内存里作为cache的。因此如果图片资源多了或大了,此方式容易引起发生内存警告从而导致自动退出的问题。

最好是通过直接读取文件路径[UIImage imageWithContentsOfFile]解决掉这个问题,应用示例:

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


备注:imageNamed方法是不能通过路径进行加载图片的,如果要通过路径加载图片可以通过下面两个方法加载,一个是URL一个是FilePath。

NSImage *image = [[NSImage alloc]initWithContentsOfURL:(NSURL *)];
NSImage *image = [[NSImage alloc]initWithContentsOfFile:(NSString *)];
用完记得  [image release];

一、加载图片问题

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方法的图片加载情况


图片资源反复使用到,如按钮背景图片的蓝色背景,这些图片要经常用到,而且占用内存少


2、不应该采用的情况:


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

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

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值