Search code examples
iphonememorymemory-managementios-simulator

Simulate memory warnings from the code, possible?


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?


Solution

  • 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 use [[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 UIViewControllers.

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