Tim Dietrich

Custom Software Developer

Home Services Blog About Contact

Xojo iOS: Handling Low-Memory Notifications

iOS does a very good job of keeping an eye on a device's resources, and especially its memory. If memory becomes low, iOS will send a notification to an app, which gives the app an opportunity to take action. If the app ignores the notification and doesn't free up memory, then there's a good chance that iOS will terminate it. To the user it will appear that the app has simply crashed.

The Xojo LowMemoryWarning Event

Xojo gives us an easy way to deal with iOS low memory notifications. The IOSApplication class, which Xojo-based iOS apps are an instance of, includes support for a LowMemoryWarning event. Using that event, you can specify the actions that should be taken to free up memory.

Let's take a look at an iOS app that handles the LowMemoryWarning event. This is a very simple iOS app which does nothing more than display a view with some text, and respond to low memory warnings. The app consists of a single view that has a Label control on it.

You can download the example Xojo project here.

Here's what the app looks like when it's running in the simulator.

I've added a LowMemoryWarning event to the App object. When the event is triggered, an iOS Message Box is displayed, warning the user that memory is low. The Xojo code for the LowMemoryWarning event looks like this:

Simulating Low Memory Warnings

You can test the event by running the app in the Simulator, and then selecting Hardware > Simulate Memory Warning (or with the Shift-Command-M keyboard shortcut). The app will display a message box, like this:

In this example, I'm simply alerting the user that memory is getting low. That doesn't do them much good.

Instead, what you really want to do is free up any expendable resources that are consuming memory. What those resources are will depend on the nature of your app. I recommend that you look for any objects that haven't been fully optimized, such as unnecessarily large arrays, images, and so on. You'll need to do some research to locate these types of objects and optimize them.

Wrapping Up

How your app responds in low memory situations is an important part of your users' overall experience. It's best to address this ahead of time, instead of having to respond to reports that your app is crashing.