Simulate memory warnings from the code, possible? [duplicate]

*爱你&永不变心* 提交于 2019-11-27 17:24:37
Brad The App Guy

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
}
Vic320

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

Post a UIApplicationDidReceiveMemoryWarningNotification notification to the default notification center:

[[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationDidReceiveMemoryWarningNotification object:nil]

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!