【object-C】About memory of imageNamed

本文探讨了iOS中图片加载的不同方法及其内存管理问题。介绍了UIImage常用加载方式的优缺点,包括缓存机制的工作原理及如何避免内存泄漏。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们常用的图片加载是不是这样的?[UIImage imageNamed:@"icon.png"]

用上面的方法加载图片可能会有问题.

原因:这种方法在application bundle的顶层文件夹寻找由供应的名字的图象 。 如果找到图片,装载到iPhone系统缓存图象。那意味图片是(理论上)放在内存里作为cache的。

如果图片多了,就傻了. 图片cache极有可能不会响应 memory warnings and release its objects

使用图片的时候一定要小心的alloc和release

如果存在大量图片导致的可能缓存问题,建议参考使用下面的方法做处理:

NSString *path = [[NSBundle mainBundle] pathForResource:@"icon" ofType:@"png"];

myImage = [UIImage imageWithContentsOfFile:path];

2023年回顾:现在看来,cache的使用是为了性能,但是滥用造成的资源浪费及挤占又会导致行性能的恶化。需要开发者合理正确的使用。

参考图片加载方式:

方法一

NSString *fileLocation = [[NSBundle mainBundle] pathForResource:fileName ofType:extension];
NSData *imageData = [NSData dataWithContentsOfFile:fileLocation];

 

[UIImage imageWithData:imageData];

方法二

[UIImage imageNamed:fullFileName]

The imageNamed: method does cache the image, but in many cases that's going to help with memory use. For example, if you load an image 10 times to display along with some text in a table view, UIImage will only keep a single representation of that image in memory instead of allocating 10 separate objects. On the other hand, if you have a very large image and you're not re-using it, you might want to load the image from a data object to make sure it's removed from memory when you're done.

If you don't have any huge images, I wouldn't worry about it. Unless you see a problem (and kudos for checking Object Allocation instead of preemptively optimizing), I would choose less lines of code over negligible memory improvements.

 

两者的区别:

区别一:

imageNamed: 只能读取包文件下的图片,不能读取Documents文件夹中的图片文件。

区别二:内存考虑
更重要的是,imageNamed 是要cache 图片

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值