可以从代码中模拟内存警告吗?

kra*_*nyk 23 memory iphone memory-management ios-simulator

我知道我可以通过从iPhone模拟器的下拉菜单中选择"模拟内存警告"来模拟模拟器上的内存警告.我甚至可以为此做一个热门钥匙.

但这不是我想要实现的目标.我想通过简单的代码来做到这一点,让我们说每5秒做一次.那可能吗?

Bra*_*Guy 56

实际上它很简单,但是它依赖于一个未记录的api调用,所以不要随它发送你的应用程序(即使它在一个无法访问的代码路径中).你所要做的就是:[[UIApplication sharedApplication] _performMemoryWarning];

此方法将使App的UIApplication对象发布UIApplicationDidReceiveMemoryWarningNotification,并在App Delegate和所有UIViewController上调用applicationDidReceiveMEmoryWarning:方法

-(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
}
Run Code Online (Sandbox Code Playgroud)

  • 为我工作5.0.1` [[UIApplication sharedApplication] performSelector:@selector(_performMemoryWarning)];` (4认同)

Vic*_*320 5

我写了一个苹果脚本,它会使模拟器出现内存错误,这有点极端,但如果你的代码存活下来,那么你可以更自信......

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
Run Code Online (Sandbox Code Playgroud)