views:

185

answers:

2

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?

A: 

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

Alex Reynolds
Yeah that was another solution, but I'm looking to a more professional way of doing it. Ppl that decide to do it that way has also to keep in mind to allocate those objects in different thread, cause doing it in the main one would simply kill the application(cause it's not gonna come back to the main loop).
krasnyk
Just allocating memory doesn't do it, you actually have to write to the memory you allocated. I had written an app to try this and discovered that after allocating 300MB on a 3GS and it was still going.
progrmr
+7  A: 

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 non-accecable 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
}
Brad Smith
+1. Nice answer.
Alex Reynolds