在 Cocoa 中实例化模型对象的层次结构时如何减少内存占用?

发布于 2024-08-23 03:05:32 字数 655 浏览 6 评论 0原文

我正在为 iPhone 编写一个测验应用程序,使用基本的 NSObject 子类来表示模型。在运行时,各种控制器实例化模型类,并用从磁盘上的 plist 读取的数据填充它们。

模型类表示多项选择测验的基本层次结构:

  • 一个应用程序有多个测验
  • 一个测验有很多问题
  • 一个问题有多个答案

当前,当 QuizController 类加载其 Quiz 对象,它用 Question 实例填充其 questions NSArray 属性,并且在初始化每个 Question 实例时,它们各自初始化自己的 NSArrayAnswer 实例。

我认识到,加载测验时不需要内存中的每个问题,我只需要 Quiz 实例的 questions 数组中某个索引处的问题。

我认为某种数据源协议或延迟加载模式将有助于减少在该系统上加载任何特定测验时产生的内存占用,但我不确定如何实现。我真的很感激社区在以下方面提出的任何建议:

这里适合使用什么模式?简短的代码片段对于我理解如何开始实现它也非常有帮助。

I'm writing a quiz application for iPhone using basic NSObject subclasses to represent the models. At runtime the various controllers instantiate the model classes and populate them with data read in from a plist on the disk.

The model classes represent the basic hierarchy of a multiple choice quiz:

  • One application has many quizzes
  • One quiz has many questions
  • One question has many answers

Currently, when the QuizController class loads its Quiz object, it populates its questions NSArray property with Question instances, and as each of those Question instances are initialized, they each initialize their own NSArrays of Answer instances.

I recognize that I don't need every question in memory when I load a quiz, I only need a question at a certain index in the Quiz instance's questions array.

I'm thinking that some sort of dataSource protocol or lazy loading pattern would help reduce the memory footprint incurred when loading up any particular quiz on this system, but I'm unsure how to implement either. I'd really appreciate any suggestions that the community had in terms of:

What pattern would be appropriate to use here? A short code snippet would also be hugely helpful for me to understand how I might begin to implement it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

葬﹪忆之殇 2024-08-30 03:05:32

我完全赞成适当的设计以最大限度地减少内存使用,但有时你也必须务实。

在旧设备上,您的应用程序将至少有 20 MB 的可用内存,因此我实际上不确定在延迟加载问题上花费大量时间是否有意义。

您可能会在没有注意到的情况下轻松地将数百个问题加载到内存中。

我的建议:从非懒惰的方式开始。使用 Instruments 查看内存使用情况。如果可以接受,那就离开它。如果您正在突破极限,那么请投入时间进行优化。

I am all for proper design to minimize memory usage, but you also have to be pragmatic sometimes.

You will have at least 20 MB of memory available for your app on older devices, so I am actually not sure if it makes sense to spend a lot of time on lazy loading questions.

You can probably easily load hundreds of questions in memory without ever noticing it.

My advice: start the non-lazy way. Look with Instruments at the memory usage. It it is aceptable then leave it. If you are pushing the limits then invest time in optimizing.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文