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:
nil
?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!
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With