Respond to Low memory warnings using 4 different ways.

Pushpsen Airekar
3 min readSep 7, 2021

The first iPhone came with 128 MB of RAM, and the latest iPhone i.e iPhone 12 Pro Max comes with a 6 GiB LPDDR4X-4266 RAM which is quite faster compared to the lower models of iPhone.

As a developer, it’s our responsibility to build an application that is suitable for all iPhone models, and it should run smooth and should be optimized for each iPhone, not only the latest ones.

To do this, we should use available free memory wisely. We should prepare our apps for low memory conditions. When the system tells us the app is running on low memory, our app should clean and remove unwanted resources, caches to free up the memory, so that the app won’t be terminated due to low memory warning.

There are various ways to identify low memory warnings.

Before responding to any low memory warning, we need to identify it first. To simulate the memory warning we need to enable the toggle when the app runs on the simulator.

To enable the logger for memory warnings, please run the app onto the simulator and then go to Debug → Simulate Memory Warning.

The simulator always runs on low memory conditions, so when you enable the logger, it will always show the log for the low memory.

1. Detect low-memory on Active View Controller

Each view controller has a built-in function func didReceiveMemoryWarning() which triggers when the view controller is facing low memory conditions.

override func didReceiveMemoryWarning {     super.didReceiveMemoryWarning()
// Remove unwanted resources that can be re-created
print("\(#function) triggered")
}

2. Detect low-memory on Application Class

AppDelegate has a built-in function func applicationDidReceiveMemoryWarning(_ application: UIApplication ) which triggers when the app is facing low memory conditions.

func applicationDidReceiveMemoryWarning(_ application: UIApplication) {     // Remove unwanted resources that can be re-created 
print("\(#function) triggered")
}

3. Detect low-memory on Custom Component using didReceiveMemoryWarningNotification to the default notification center.

In this, we will observe the notification in our custom component using the notification center, so whenever it triggers, we’ll be able to notify for low-memory warnings.

import UIKit
struct MemoryMonitor {
init() { NotificationCenter.default.addObserver(forName: UIApplication.didReceiveMemoryWarningNotification, object: nil, queue: nil) { notification in print("\(#function) triggered with \(notification) notification")
}
}
}

4. Dispatch Source for memory pressure events.

This is the most advanced technique to monitor the memory pressure for low memory issues inside the application. It even lets us distinguish the severity of memory pressure by providing the conditions such as:

  1. warning
  2. critical
  3. normal
  4. all

To implement it, we’ll design a singleton class MemoryPressureMonitor, which will listen to the events for DispatchSource.

import Foundationclass MemoryPressureMonitor {static let shared = MemoryPressureMonitor()private let dispatchSource = DispatchSource.makeMemoryPressureSource(eventMask: [.warning, .critical])private init() {
dispatchSource.setEventHandler { [weak self] in
if
let event = self?.dispatchSource.data, self?.dispatchSource.isCancelled == false {
switch event {
case .warning:
print("MemoryPressureMonitor: Low memory warning")
case.critical:
print("MemoryPressureMonitor: Critical memory warning")
default:
print("MemoryPressureMonitor: Unknown Event")
}
}
}
dispatchSource.activate()
}
deinit {
dispatchSource.cancel()
}
}

Download the sample app for reference.

Please download the sample app from the link. You will be able to distinguish the different ways by searching the titles mentioned in the article in the Xcode project mentioned in the repository.

--

--

Pushpsen Airekar

Product Engineer,  iOS Developer @ CometChat Inc, Passionate iOS developer from India 🇮🇳. with a great test in UX design.