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? 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.
我在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.
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.