iOS, Objective-C, Swift, Design and Whatever Comes in Mind

Overlooked API of the Day: NSCache

I am almost sure that you have stumbled upon the method didReceiveMemoryWarning. It gets added to every UIViewController that you create usind a template from Xcode.

Image of the default code in didReceiveMemoryWarning

Depending on the memory consumption of your ViewController, it's the systems way of telling you "Hey, please use less memory or I am forced to kill your process". This might be a good time to drop references to cached images that can be re-loaded from disk or via network.

Your app also gets a notification called UIApplicationDidReceiveMemoryWarningNotification when the device will run our of memory. Every object can listen for this notification and act accordingly.

If you do not want do deal with this kind of situation by yourself NSCache assist you. NSCache works like a regular dictionary but will drop elements once the memory pressure gets too high.

You can, for example, put downloaded images into a NSCache. They may get purged during usage of your app. In this case you need to re-download them, which is not great but certainly better than crashing.

You can find the documentation of NSCache over here. And if you need an image cache that writes the cache to disk and manages all of the downloading and storing things for you, please take a look at Kingfisher

"Overlooked API of the Day: NSCache".

Overlooked API of the Day: NSOrderedSet

As you know, an Array stores elements while preserving the order of their addition. You also may have learned that Sets are perfect for storing a collection of data where every element is unique. Because of its implementation it is also easy to perform boolean operations on two Sets (like computing the intersection or difference of two Sets). However, Sets will not preserve the order of their elements. What is more, they gain their efficiency only from not remembering information about the order.

This is where NSOrderedSet comes into play. According to Apples documentation, it acts as a Set (containing an element only once) whilst preserving the order of their additions.

Its counterpart NSMutableOrderedSet is the mutable addition to the datatype.

"Overlooked API of the Day: NSOrderedSet".

Overlooked API of the Day: NSCountedSet

Have you ever encountered the issue where you had a sequence of things, you needed the elements only once and must know what elements are duplicates? And how often they occure?

Take a look as NSCountedSet! For example when combining multiple collections (Sets), you can determine which elements are contained multiple times. That technique can be used to calculate the intersection of collections in a straight foreward way 🙃

Apples documentation can be found here.

"Overlooked API of the Day: NSCountedSet".