I'm at the part of my development process for tracking down crashing and memory leaks. As a strategy, do you put any NSLog messages or notifications of some such into didReceiveMemoryWarning: ? The documentation for this method is rather sparse. Is it accurate to say that before a crash will happen, the UIViewController will trigger that method? Is that a starting point before even going forward with Instruments?
OK, several things to note:
- didReceiveMemoryWarning will be called before an out-of-memory crash. Not other crashes. If you handle the warning properly and free up memory, then you can avoid the out-of-memory condition and not crash.
- You can manually trigger a memory warning in the simulator under the Hardware menu. Highly recommend doing this to flush out problems.
- Instruments helps you debug leaks (though not all of them) - it's not really that useful for crashes.
- No, I don't personally use NSLog - I just breakpoint the memory warnings when I'm debugging.
The purpose of didReceiveMemoryWarning is to give you a chance to free memory or pop views to avoid a crash. You will not receive it at any predictable point because it depends on what the user is doing. For example, if the user is listening to the iPod, there is less available memory and you will receive it sooner.
The general rule of thumb is that you have about 8MB of RAM to work with. When you get close to that you can expect the event to be raised. If you are taking up that much RAM deliberately you should have a plan to do something about it.
Thanks for this tip....but what do you do if your application isn't the one that has hogged up all the memory? Say your program launches and you get this didReceiveMemoryWarning but it is the first time your program launches.
didReceiveMemoryWarning
is absolutely useless.
There's no guarantee that if you free up memory (even all of it) that you won't get killed.
In my bitter experience it usually works like this on 2.x/3.0:
mediaserverd leaks a bunch of memory
my app gets killed
Unfortunately, the reaper never thinks of killing mediaserverd.
So if the memory usage isn't your fault, you've really only got two choices:
ask the user to reboot (user assumes it's your fault, writes a scathing review)
hope the culprit crashes (mediaserverd often obliges!)
What would be some actually code-fragments that you would put inside didReceiveMemoryWarning?
I can't really think of a single thing to "free". Everything I'm doing has either been:
Immediately freed as soon as I'm done with it.
Can't be freed... because I still need it, and my app is still using it.