触发内存警告的最简单方法是什么?
答案 0 :(得分:7)
答案 1 :(得分:4)
[[NSNotificationCenter defaultCenter] postNotificationName:
@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
答案 2 :(得分:1)
我喜欢在调试模式中隐藏在我的应用中隐藏的内容,例如在我的UI的某个区域上点击三次触发此操作:
- (void) simulateMemoryWarning:(UITapGestureRecognizer *)gesture {
[[NSNotificationCenter defaultCenter] postNotificationName:TriggerManualMemoryWarningNotification object:nil];
}
然后在我的app delegate中:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveManualMemoryWarning:) name:TriggerManualMemoryWarningNotification object:nil];
和
- (void) didReceiveManualMemoryWarning:(NSNotification *)notification {
#ifdef DEBUG
SEL memoryWarningSel = @selector(_performMemoryWarning);
if ([[UIApplication sharedApplication] respondsToSelector:memoryWarningSel]) {
[[UIApplication sharedApplication] performSelector:memoryWarningSel];
}else {
NSLog(@"%@",@"Whoops UIApplication no loger responds to -_performMemoryWarning");
}
#else
NSLog(@"%@",@"Warning: performFakeMemoryWarning called on a non debug build");
#endif
}
答案 3 :(得分:0)
在模拟器中,您可以模拟一个......
从设备中,您可能希望分配大量内存(例如,通过malloc
)。
您需要按步骤执行此操作,否则应用程序可能会在没有内存警告的情况下崩溃。
答案 4 :(得分:0)
Swift 版本:
NotificationCenter.default.post(Notification(name: UIApplication.didReceiveMemoryWarningNotification, object: UIApplication.shared, userInfo: nil))
观察者
let cancellable = NotificationCenter.default
.publisher(for: UIApplication.didReceiveMemoryWarningNotification)
.sink { _ in
print("Received memory warning")
}
我发现它在测试中很有用。