[UIImage imageNamed...] 和 [UIImage imageWithData...] 的区别? [英] Difference between [UIImage imageNamed...] and [UIImage imageWithData...]?

查看:28
本文介绍了[UIImage imageNamed...] 和 [UIImage imageWithData...] 的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从文件系统将一些图像加载到我的应用程序中.有两种简单的方法可以做到这一点:

I want to load some images into my application from the file system. There's 2 easy ways to do this:

[UIImage imageNamed:fullFileName]

或:

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

[UIImage imageWithData:imageData];

我更喜欢第一个,因为它的代码少了很多,但是我看到有人说图像被缓存了,这种方法使用了更多的内存?由于我不信任大多数其他论坛上的人,我想我会在这里问这个问题,是否有任何实际区别,如果有,哪个更好"?

I prefer the first one because it's a lot less code, but I have seen some people saying that the image is cached and that this method uses more memory? Since I don't trust people on most other forums, I thought I'd ask the question here, is there any practical difference, and if so which one is 'better'?

我尝试使用对象分配工具分析我的应用程序,但我看不出任何实际差异,尽管我只在模拟器中尝试过,而不是在 iPhone 本身上尝试过.

I have tried profiling my app using the Object Allocation instrument, and I can't see any practical difference, though I have only tried in the simulator, and not on an iPhone itself.

推荐答案

这取决于您对图像的处理方式.imageNamed: 方法确实缓存了图像,但在许多情况下这将有助于内存使用.例如,如果你加载一个图像 10 次以在 table view 中与一些文本一起显示,UIImage 将只在内存中保留该图像的单个表示,而不是分配 10 个单独的对象.另一方面,如果您有一个非常大的图像并且您不重复使用它,您可能希望从数据对象加载图像以确保完成后从内存中删除它.

It depends on what you're doing with the image. 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.

这篇关于[UIImage imageNamed...] 和 [UIImage imageWithData...] 的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆