IOS 开发: 如何在设备上引入低内存警告?

我想在低内存条件下测试我的应用程序功能,但很难测试。当应用程序在设备上而不是模拟器上运行时,我如何在视图中引入触发 did ReceiveMemory 方法的低内存警告?或者,在这些可能的条件下,我有什么方法可以测试我的应用程序?

我不能使用模拟器的原因是我的应用程序使用游戏中心和邀请不工作的模拟器。

38780 次浏览

Theres a menu command that will invoke it.

Hardware > Simulate Memory Warning from the simulator.

The iOS Simulator's Simulate Memory Warning menu item allows you to simulate a memory warning.

enter image description here

To test on a device, just add some code that periodically allocates large chunks of memory without freeing it (i.e. 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.

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.

Using Instruments, use the menu item: Instrument -> Simulate Memory Warning.

To use Instruments on your app from Xcode, use the Product -> Profile menu item.

I've re-written Enzo Tran's answer in Swift:

UIControl().sendAction(Selector(("_performMemoryWarning")), to: UIApplication.shared, for: nil)

Converted @ChikabuZ to swift 3:

UIControl().sendAction(Selector(("_performMemoryWarning")), to: UIApplication.shared, for: nil)

If someone, for whatever reason, tries to do this in Swift 3 - here is how to allocate 1.2 GB of ram.

   for i in 0...1200 {
var p: [UnsafeMutableRawPointer] = []
var allocatedMB = 0
p.append(malloc(1048576))
memset(p[allocatedMB], 0, 1048576);
allocatedMB += 1;
}

Swift 4:

UIApplication.shared.perform(Selector(("_performMemoryWarning")))

Can execute the above in response to an event/notification. For example:

    Button(action: {
UIApplication.shared.perform(Selector(("_performMemoryWarning")))
}, label: {
Image(systemName: "memorychip")
})

If someone, for whatever reason, tries to do this in Swift 4 - here is how to allocate 1.2 GB of ram.

let d = Data.init(repeating: 100, count: 1200000000)
  • This is helpful to trigger a warning alert in other apps