Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In what method should I recreate resources after didReceiveMemoryWarning?

I have a view controller that has a private NSArray variable. The variable is initialised in the viewDidLoad method. A few questions arise for the case when the didReceiveMemoryWarning is called:

  1. Should I set the private variable to nil?
  2. If I set it to nil in what method must it be recreated? Does the view controller call the viewDidLoad method to recreate it?

I'm asking because other methods of the view need this variable and won't work if it's nil.

Thank you!

like image 664
planewalker Avatar asked May 31 '13 10:05

planewalker


2 Answers

Typically you unload a private property by assigning nil via the setter (e.g. self.propertyName = nil). Or you could set the ivar to nil after calling release, e.g. [_propertyName release]; _propertyName = nil;, but the former is preferable.

The didReceiveMemoryWarning method is called when there is a low memory situation. It is called on every view controller, including the one(s) responsible for the currently visible UI!

Therefore, you can't just unload data arbitrarily when you get a call to didReceiveMemoryWarning -- the view controller might need that data if it is currently visible on the display.

The general principle is that didReceiveMemoryWarning can get rid of any resources it can to assist freeing up memory, but only those that aren't immediately needed. For example, in an OpenGL game you wouldn't unload textures that are currently visible on the display. However, see my last paragraph.

Typically you reload the resources by checking they are loaded when you need them, and if not, loading them.

It's not worth niling/releasing tiny resources such as a single normally sized string. You should concentrate on items taking up significant amounts of memory.

Recent advances in behind the scenes memory management mean you're less likely to need to actually unload data these days - the operating system can unload and reload uncompressed image data and the like behind the scenes.

As Hot Licks mentions, the simulator has an option for simulating a memory warning. It's worth triggering this memory warning at various points in your app to see how it behaves.

like image 166
occulus Avatar answered Sep 21 '22 16:09

occulus


Create custom getter that load data lazily. Something such as this snippet is good for non-mutithreading eviroment:

- (NSArray*) dataArray {
  if(_dataArray) return _dataArray;

  _dataArray = [self lordata];
  return _dataArray;
}

In this way data are always reloaded if you "release" them in memory warnings

like image 37
Andrea Avatar answered Sep 24 '22 16:09

Andrea