Preventing objects from using infinite memory

The first type of memory leak is one where an object is allowed to take up an endless amount of memory without any restrictions. A typical example of this is a cache. When you implement a cache that holds on to certain model objects, API responses, or other data that was expensive to obtain in the first place, it's easy to overlook the fact that you have just built yourself a memory leak.

If your user is using your app and your cache object keeps caching more and more data, the device will eventually run out of memory. This is a problem because if the app doesn't free the memory in time, it will be terminated by iOS to make sure that essential processes and other apps don't suffer because of your app's out-of-control memory usage.

Luckily, it's easy to solve issues such as these. The operating system will notify your app through NotificationCenter any time it needs you to free up memory. Listening to this notification and purging any cached data you can recreate or reload will prevent your app from hogging memory and, ultimately, it prevents your app from being terminated due to memory reasons.

Here is a straightforward example of an image cache class that purges its cache when memory is tight:

class ImageCache: NSObject {
  var cache = [UIImage]()

  override init() {
    super.init()

    NotificationCenter.default.addObserver(self, selector: #selector(purgeCache), name: UIApplication.didReceiveMemoryWarningNotification, object: nil)
  }

  deinit {
    NotificationCenter.default.removeObserver(self, name: UIApplication.didReceiveMemoryWarningNotification, object: nil)
  }

  @objc func purgeCache() {
    cache.removeAll()
  }
}

All you need to do is listen for the UIApplication.didReceiveMemoryWarningNotification notification and purge any data that you can recreate when needed. Even though it's technically not required, this sample unsubscribes the cache from the memory warning notifications when it's deallocated. Since iOS 9, the OS itself should take care of this but this behavior has proven to be somewhat unpredictable so unsubscribing explicitly avoids potential reference cycles, which is the next type of memory leak to explore.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.151.126