Search code examples
iphonecocoa-touchlazy-loadingcocoa-design-patterns

How to reduce memory footprint when instantiating a hierarchy of model objects in Cocoa?


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.


Solution

  • 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.