What things should be released in didReceiveMemoryWarning method?

didreceivememorywarning, ios, objective-c

Solution

You can release anything here that you can easily recreate.

- Data structures that are built or serialized from the store.

- Used-entered data if you've cached it

- Data from the network if you've cached it.

A common idiom in iOS software is to use lazy initialization.

With lazy init you don't initialise ivars in the init method, you do it in the getter instead after a check on wether it already exists:

@interface ViewController ()
@property (strong,readonly)NSString *testData;
@end

@implementation ViewController

@synthesize testData=_testData;

// Override the default getter for testData
-(NSString*)testData
{
    if(nil==_testData)
        _testData=[self createSomeData];
    return _testData;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];

    _testData=nil;
}

In this situation the memory for testData is initialised on it's first use, discarded in `didReceiveMemoryWarning`, then safely re-created the next time it's required.

Problem

What I've done is to release anything from a view in this method, but my intuition told me I might do it wrong. In most cases, what kind of resources should be killed in `didReceiveMemoryWarning`?

Original source

Related problems