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

use*_*299 4 objective-c didreceivememorywarning ios

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

在大多数情况下,应该杀死什么样的资源 didReceiveMemoryWarning

Dav*_*idA 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;
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,testData的内存在首次使用时被初始化,丢弃didReceiveMemoryWarning,然后在下次需要时安全地重新创建.