Simulate memory warnings from the code, possible?

2019-01-12 23:50发布

This question already has an answer here:

I know i can simulate a memory warning on the simulator by selecting 'Simulate Memory Warning' from the drop down menu of the iPhone Simulator. I can even make a hot key for that.

But this is not what I'd like to achieve. I'd like to do that from the code by simply, lets say doing it every 5 seconds. Is that possible?

4条回答
地球回转人心会变
2楼-- · 2019-01-13 00:11

I wrote an apple script that will hammer the simulator with memory errors, it is a bit extreme but if your code survives, then you can be more confident...

on run
repeat 100 times
    tell application "System Events"
        tell process "iOS Simulator"
            tell menu bar 1
                tell menu bar item "Hardware"
                    tell menu "Hardware"
                        click menu item "Simulate Memory Warning"
                    end tell
                end tell
            end tell
        end tell
    end tell
    delay 0.5
end repeat
end run
查看更多
叼着烟拽天下
3楼-- · 2019-01-13 00:15

It is pretty easy actually, however it relies on an undocumented api call, so dont ship your app with it (even if it is in a inaccessible code path). All you have to do is: [[UIApplication sharedApplication] _performMemoryWarning];

This method will have the App's UIApplication object post the UIApplicationDidReceiveMemoryWarningNotification and call the applicationDidReceiveMEmoryWarning: method on the App Delegate and all UIViewController's

-(IBAction) performFakeMemoryWarning {
  #ifdef DEBUG_BUILD
    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
}
查看更多
不美不萌又怎样
4楼-- · 2019-01-13 00:22

Post a UIApplicationDidReceiveMemoryWarningNotification notification to the default notification center:

[[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationDidReceiveMemoryWarningNotification object:nil]
查看更多
Deceive 欺骗
5楼-- · 2019-01-13 00:23

Just alloc-init big objects in a loop, and never release them. That should trigger a memory warning pretty quickly, I'd imagine.

查看更多
登录 后发表回答