[英]iOS Development: How can I induce low memory warnings on device?
I'd like to test my app functions well in low memory conditions, but it's difficult to test. 我想在低内存条件下测试我的应用程序功能,但很难测试。 How can I induce low memory warnings that trigger the didReceiveMemoryWarning method in my views when the app is running on the device, not the simulator?
当应用程序在设备上运行而不是模拟器时,如何在我的视图中引发触发didReceiveMemoryWarning方法的低内存警告? Or what are some ways I can test my app under these possible conditions?
或者我可以在这些可能的条件下测试我的应用程序有哪些方法?
The reason I can't use the simulator is my app uses Game Center and invites don't work on the simulator. 我无法使用模拟器的原因是我的应用程序使用游戏中心和邀请不在模拟器上工作。
You can call the private method : 您可以调用私有方法 :
[[UIApplication sharedApplication] performSelector:@selector(_performMemoryWarning)];
Just remember to use it on debug only, or else your app will get rejected. 只记得在调试时使用它,否则你的应用程序将被拒绝。
iOS模拟器的Simulate Memory Warning
菜单项允许您模拟内存警告。
Using Instruments, use the menu item: Instrument -> Simulate Memory Warning. 使用仪器,使用菜单项:仪器 - >模拟内存警告。
To use Instruments on your app from Xcode, use the Product -> Profile menu item. 要在Xcode上使用应用程序中的Instruments,请使用Product - > Profile菜单项。
我在Swift中重写了Enzo Tran的答案 :
UIControl().sendAction(Selector(("_performMemoryWarning")), to: UIApplication.shared, for: nil)
将@ChikabuZ转换为swift 3:
UIControl().sendAction(Selector(("_performMemoryWarning")), to: UIApplication.shared, for: nil)
Theres a menu command that will invoke it. 这是一个会调用它的菜单命令。
Hardware > Simulate Memory Warning
from the simulator. Hardware > Simulate Memory Warning
从模拟器Hardware > Simulate Memory Warning
。
To test on a device, just add some code that periodically allocates large chunks of memory without freeing it (ie leak on purpose). 要在设备上进行测试,只需添加一些代码,这些代码会定期分配大块内存而不会释放它(即故意泄漏)。 You can do this in a separate thread, or in response to a timer, or using whatever mechanism that best allows you to test and observe the behavior of your application.
您可以在单独的线程中执行此操作,或者响应计时器,或使用最适合您测试和观察应用程序行为的任何机制。
You might also choose to create a separate app that does something similar and is designed to run in the background, if you'd like to easily reuse this and/or test with multiple applications. 如果您希望轻松地重复使用和/或测试多个应用程序,您也可以选择创建一个单独的应用程序来执行类似的操作并设计为在后台运行。
如果有人出于某种原因试图在Swift 4中这样做 - 这里是如何分配1.2 GB的内存。
let d = Data.init(repeating: 100, count: 1200000000)
If someone, for whatever reason, tries to do this in Swift 3 - here is how to allocate 1.2 GB of ram. 如果有人出于某种原因试图在Swift 3中这样做 - 这里是如何分配1.2 GB的内存。
for i in 0...1200 {
var p: [UnsafeMutableRawPointer] = []
var allocatedMB = 0
p.append(malloc(1048576))
memset(p[allocatedMB], 0, 1048576);
allocatedMB += 1;
}
Swift 4: 斯威夫特4:
UIApplication.shared.perform(Selector(("_performMemoryWarning"))) UIApplication.shared.perform(选择器(( “_ performMemoryWarning”)))
Can execute the above in response to an event/notification. 可以执行上述操作以响应事件/通知。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.