【问题标题】:Release graphics when app entered to background mode当应用程序进入后台模式时释放图形
【发布时间】:2012-02-27 15:36:53
【问题描述】:

在 Apple 文档中,您可以发现 Apple 建议在您的应用进入后台模式时释放图像等大量数据。
如何从UIViews 和其他数据中释放图像?
如何以正确的方式从所有viewController 发布来自UIViews 的图像?
应用收到applicationWillResignActive消息时如何恢复数据?

如果有人有一个很好的例子或链接,请展示它。

【问题讨论】:

  • 为什么有这么多反对票?好的,这是一个模糊的问题,但实际上是一个很好的问题。很高兴看到一个好的答案(即对初学者有用)。

标签: iphone ios cocoa-touch ipad


【解决方案1】:

添加到应用程序委托 2 方法

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_APP_BACKGROUND object:nil];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_APP_BACKGROUND object:nil];
}

使用方法制作 BaseViewController:

- (id)init
{
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillForeground) name:NOTIFICATION_APP_FOREGROUND object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidBackground) name:NOTIFICATION_APP_BACKGROUND object:nil];
    }

    return self;
}


- (void)appDidBackground {
}

- (void)appWillForeground {

}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}

从 BaseViewController 子类化所有视图控制器。在方法 appDidBackground 你应该释放不需要的数据,在 appWillForeground - 恢复它

【讨论】:

  • 1.有人告诉我,如果使用[UIImage imagenamed:@"image.png"] - 这不会从内存中释放图像。 2.如何保存你的数据然后恢复。使用 NSUserDefaults?如果您使用 coreData 很容易。但是例如如何保存 nsarray,我可以将它保存到 nsuserdefaults 或 plist 文件。什么是正确的方法?
  • 1. [UIImage imageNamed] 缓存所有图像。它可能会在内存警告时被释放。 2. 要保存大量数据,您应该使用 coredata,对于少量数据 - NSUserDefaults 是个好方法。如果你想保存一个包含一些自定义对象的数组(在 NSUserDefaults 中),你应该为其中的每个自定义类实现 NSCoding 协议。
  • 如何释放使用 loadView 添加的 UIView。有人说需要使用viewDidUnload,但是app进入后台模式这个方法不会调用。
猜你喜欢
  • 2013-03-09
  • 2011-05-13
  • 2018-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多