[UIImage imageNamed ...]和[UIImage imageWithData ...]之间的差异? [英] Difference between [UIImage imageNamed...] and [UIImage imageWithData...]?

查看:306
本文介绍了[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次以及在表视图中显示一些文本,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天全站免登陆