Reputation: 143
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
?
Upvotes: 4
Views: 7047
Reputation: 3172
You can release anything here that you can easily recreate.
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.
Upvotes: 17
Reputation: 603
One example i am posting...which i have copied from somwhere... it might give you some idea..
- (void)didReceiveMemoryWarning {
// Release anything that's 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];
}
Upvotes: 1
Reputation: 9842
You should use Instruments
feature to test which objects are taking more memory in your application. Then in didReceiveMemoryWarning
delegate callback dealloc
, release
those objects.
Usually media files (audio, video, images) take more memory than other kind of things. So you should focus them first.
Here is the link of tutorial about Xcode Instruments
Upvotes: 3