Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What things should be released in didReceiveMemoryWarning method?

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?

like image 292
user3586299 Avatar asked Dec 01 '22 01:12

user3586299


1 Answers

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.

like image 162
DavidA Avatar answered May 14 '23 09:05

DavidA