What things should be released in the didReceiveMemoryWarning method?

I did this to release something from the view in this method, but my intuition told me that I could do it wrong.

In most cases, what resources should be killed in didReceiveMemoryWarning?

+4
source share
3 answers

Here you can release everything that can be easily recreated.

  • Data structures that are built or serialized from storage.
  • Used data if you cached it
  • Data from the network, if you cached it.

A common idiom in iOS software is the use of lazy initialization.

init ivars init, getter , :

@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;
}

testData , didReceiveMemoryWarning, .

+16

Instruments , . didReceiveMemoryWarning dealloc, release .

(, , ) , . .

Xcode Instruments

+3

, ... somwhere... .

- (void)didReceiveMemoryWarning {

    // Release anything that not essential, such as cached data (meaning
    // instance variables, and what else...?)

    // Obviously can't access local variables such as defined in method
    // loadView, so can't release them here We can set some instance variables
    // as nil, rather than call the release method on them, if we have defined
    // setters that retain nil and release their old values (such as through use
    // of @synthesize). This can be a better approach than using the release
    // method, because this prevents a variable from pointing to random remnant
    // data.  Note in contrast, that setting a variable directly (using "=" and
    // not using the setter), would result in a memory leak.
    self.myStringB = nil;
    self.myStringD = nil;
    [myStringA release];// No setter defined - must release it this way
    [myStringC release];// No setter defined - must release it this way

    /* 3. MUST CONFIRM: NOT necessary to release outlets here - See override of
       setView instead.
    self.labelA = nil;
    self.imageViewA = nil;
    self.subViewA = nil;
     */
    // Releases the view if it doesn't have a superview
    [super didReceiveMemoryWarning];
}
+1
source

Source: https://habr.com/ru/post/1543357/


All Articles