1

我是 IOS 新手,来自个人电脑,我正在尝试管理内存和电池资源。

我有一个很轻的 UIImageView 子类(它是一个带有一些方法的图像占位符)。这个子类被反复添加到几个根视图中,或者从几个根视图中删除。我在每个根视图上都持有对子类的 IBOutlet 引用。

你会:

  • 只需从根视图中添加/删除子类(并将其保存在内存中)?

或者

  • 每次都创建和销毁子类实例(释放内存但额外的工作)?

这值得考虑还是我什么都不担心?

如果 UIImageView 子类非常大,您的答案是否相同?

有没有办法衡量这些问题?

4

4 回答 4

2

通常,您可以UIImageView在 iOS 上无视地使用。 UIImageView只不过是带有一些处理图像的方法的剪辑区域。

占用更多内存的资源是UIImage包含在 iOS 中的UIImageView,这些是由 iOS 缓存的。

所以创建UIImageViews和销毁它们几乎没有成本,只要注意释放它们并且不要泄漏内存,除非你有数百个它们,否则你应该没问题。

子类“大”无关紧要,一个类中的代码永远不会加载超过一次。如果班级有很多额外的状态 - 这会占用一些内存,但我无法在UIImageView.

于 2012-08-10T13:14:03.827 回答
1

You better just keep it in memory. User experience will be much better if you don't slow down the device by continuously recreating the image view. One single poor UIImageView instance is not memory heavy enough to worth the time and effort to recreaty all the time.

于 2012-08-10T13:38:56.347 回答
1

Keeping it an memory to improve performance isn't as much of a hit as you would think - taken from the other answers you have. But you should remove it from memory if you get a memory warning, and provide a way to bring it back to life as needed.

于 2012-08-10T13:39:29.560 回答
0

I would go with your first option, keeping it in memory. This is just because I think it is handy to keep my views alive and reuse them. This means that they will remember their state and content and that helps out in many cases. I usually write methods to reset the content or refresh it when needed.

Keeping it in memory might also increase the loading of the view slightly, but usually you do not notice the difference, and I see people using both ways.

And yes, I would say you are worrying a bit too much, especially if you think this decision would affect battery.

Regarding memory management, keeping the imageview in memory or releasing/recreating consumes the exact same amount of memory as long as you only have one imageview that you are using. The only difference is that you are allocating and releasing it repeatedly if you are recreating it.

You could however get memory issues if you start creating new imageviews every time the user opens them and never letting go of them, but that means you are doing something fundamentally wrong in your programming.

As long as you know what you are doing, no need to worry about the amount of memory in a case like this - there's plenty. Start worrying if you are handling large images.

Especially if you use ARC there is not much to worry about, just start hacking away. If you are managing memory manually, I do recommend trying to reuse stuff because that causes less headache and risk of giant leaking. Use leaktools and analyze tool to make sure in this case.

于 2012-08-10T13:35:29.207 回答