Responding to memory pressure

Memory & ARC Senior Swift 5.0+ iOS 17+ Reviewed By Alok Singh

Pick the fix

An image-heavy feed gets memory warnings and is killed in the background. Best plan?

Options
Hint 1 of 1

What does a decoded image cost?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A Downsample to display size, cache in NSCache with a cost limit, and clear caches on warnings and backgrounding

Correct. It lowers peak memory and responds to pressure.

Why not the others?
  • B Cache every image in a Dictionary for speed. A Dictionary never evicts, so memory only grows.
  • C Load full-resolution images and rely on contentMode to shrink them. The full image is still decoded into memory.
  • D Ignore warnings, because iOS manages memory. The system terminates apps that ignore pressure.

30-second answer

Keep memory low before the warning comes: downsample images to their display size, cache decoded images in NSCache with a cost limit, and free caches on didReceiveMemoryWarning or when the app goes to the background. The system kills apps that use too much memory, especially in the background.

Practise saying it · 45 s. No recording, just a timer

Explain how you handle memory pressure.

Say your answer out loud, then check which of these points you covered:

  • Downsample
  • NSCache with limits
  • Purge on warnings
  • Measure

Deep dive

Decoded image memory is width × height × 4 bytes, regardless of file size.

Use ImageIO thumbnail APIs to downsample without decoding the full image.

NSCache evicts automatically under pressure, and is thread-safe.

Watch the memory gauge and the jetsam reports in Organizer.

Common mistakes

  • Caching full-resolution images in a Dictionary.
  • Scaling large images down only with contentMode.

Senior take & follow-ups

Seniors calculate decoded image size and design caches with limits.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why does a 200 KB JPEG use 48 MB?

    Show hint

    Decoded size depends on pixels, for example 4000×3000×4.

  2. Where do you see memory terminations?

    Show hint

    Xcode Organizer and MetricKit.

Suggest a fix if something here is wrong or out of date.