【问题标题】:Xcode Allocations Instrument - Listening to Memory WarningsXcode Allocations Instrument - 监听内存警告
【发布时间】:2013-02-16 10:16:49
【问题描述】:

我正在使用分配工具来提高我的应用程序的性能。我想注意 memoryWarnings 以确保我的应用不会占用太多内存或崩溃。

我希望我的整个应用程序都能收听 memoryWarings。我知道我可以用它来收听某些警告,但是下面的代码会收听所有内容吗?另外,我需要在哪里实现它?是需要放在每个 View Controller 中还是可以放在 App Delegate 中?

- (id)init {
if ((self = [super init])) 
    {
    _cache = [NSMutableDictionary new];
    [[NSNotificationCenter defaultCenter] addObserver:self 
    selector:@selector(memoryWarning:) 
    name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
    }
return self;
}

我知道我需要实现监听 memoryWarnings 的方法。这会听所有的内存警告吗?另外,我需要把它放在每个 viewController 中吗?或者我可以将它放在 AppDelegate 中吗?

- (void)memoryWarning:(NSNotification*)note {
    [_cache removeAllObjects];
}

任何指导都会很棒!谢谢!

【问题讨论】:

  • 我建议改变你的方法并为此使用NSCache。当应用程序内存不足时,它会自动删除不需要的缓存条目。

标签: iphone ios objective-c xcode memory-management


【解决方案1】:

你的视图控制器已经有了监听内存警告的方法

 - (void)didReceiveMemoryWarning
 {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];

// Release any cached data, images, etc that aren't in use.
}

【讨论】:

  • 谢谢,我需要调用 [_cache removeAllObjects];在 didReceiveMemoryWarning 方法中?
  • 没有。 [_cache release] 。它将在 _cache 字典中的所有对象上发送释放消息
  • 是的。我不知道你的 _cache 的用途。 didReceiveMemoryWarning 方法在内存充足时被系统调用。如果您需要进一步缓存,请不要等待didReceiveMemoryWarning 释放dealloc 本身中的_cache
  • 老实说,我不知道我为什么需要它 - 遵循一个建议在 memoryWarnings 时清除缓存的教程
猜你喜欢
  • 1970-01-01
  • 2011-12-05
  • 2016-10-02
  • 2011-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-01
相关资源
最近更新 更多