在applicationWillResignActive中发送内存警告

时间:2011-10-06 00:07:56

标签: objective-c ios memory appstore-approval

几天前,我在SO上发现了一个不错的代码片段来测试内存警告,只需每10秒发送一次UIApplicationDidReceiveMemoryWarningNotification通知。

我真的很喜欢这个想法并采用它只在应用切换到后台时发出通知,因为它可以更容易清理一些内存,因为每个UIViewController都会收听此通知(并执行我也受益于一些记忆清洁。)

由于我是一个懒惰的程序员,我想知道Apple是否允许这种技巧。 从技术上讲,这不是私有的API使用,我甚至怀疑他们在测试期间发现了这些东西,但是,我并不是100%肯定这一点。我正在使用的代码如下所示:

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Do some other stuff, unrelated to the question

    [[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationDidReceiveMemoryWarningNotification object:application];
}

2 个答案:

答案 0 :(得分:1)

我在我的App iFerien Deluxe中做了同样的事情,它完成了批准过程,没有任何问题。 我个人认为,这对Apple来说是一个问题。 但是在我当前的应用程序中,我试图避免这种情况,因为它看起来有点hacky,因为你最好不得不在applicationWillResignActive中手动释放你的内存。

答案 1 :(得分:0)

可能可能,但这有点不好。

您可以轻松编写自己的通知。只需打开项目的预编译头文件(通常在“其他来源”或“支持文件”下,并确保它包含此#define。

#ifdef __OBJC__
    #define MyApplicationDidReceiveMemoryWarning @"myMemoryWarningString"
#endif

PCH有效地包含在您编译的每个文件中。在applicationDidFInishLaunch:withOptions:

中设置NSTimer
[NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(sendMemoryNotification) userInfo:nil repeats:YES];

在sendMemoryNotification方法中,只需发布​​通知

-(void)sendMemoryNotification
{
    [[NSNotificationCenter defaultCenter] postNotification:MyApplicationDidReceiveMemoryWarning];
}

任何拥有重要数据的类都注册为NSNotificationCenter中密钥的观察者。