didReceiveMemoryWarning方法应该发布什么内容?

时间:2014-06-05 07:39:11

标签: ios objective-c didreceivememorywarning

我所做的就是从这个方法的视角中释放任何东西,但我的直觉告诉我,我可能做错了。

在大多数情况下,应该在didReceiveMemoryWarning中杀死哪种资源?

3 个答案:

答案 0 :(得分:16)

您可以在此处发布任何可以轻松重新创建的内容。

  • 从商店构建或序列化的数据结构。
  • 使用过的数据(如果已缓存)
  • 如果您已将其缓存,则来自网络的数据。

iOS软件中常见的习惯用法是使用延迟初始化。

使用lazy init你不会在init方法中初始化ivars,而是在检查之后在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中丢弃,然后在下次需要时安全地重新创建。

答案 1 :(得分:3)

您应该使用Instruments功能来测试哪些对象在您的应用程序中占用更多内存。然后在didReceiveMemoryWarning委托回调deallocrelease这些对象。

通常,媒体文件(音频,视频,图像)比其他类型的内容占用更多内存。所以你应该首先关注它们。

Here is the link of tutorial about Xcode Instruments

答案 2 :(得分:1)

我发帖的一个例子......我从某个地方复制过......它可能会给你一些想法..

- (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];
}