In this article we’ll see how we can make a simple cache manager in swift.

The goal is to store NSCoding compliant objects to the phone and restore them afterwards.
We’ll use an identifier string that is provided to the “save” function to generate unique filename to save the object on the phone.

The CacheManager implementation is pretty straightforward

  • “sharedInstance” : a computed property  for the singleton
  • “filenameFromIdDico” property : a dictionary used to track the unique filename associated to an object identifier
  • “objectMaxId” : a private property that represent the current object maximum id
  • “init()” and “encodeWithCoder()” : the methods to be NSCoding compliant
  • “saveObject()” and “loadObject()” methods to manipulate the objects we want to cache
  • “saveToDevice()” : a  method used to save the CacheManager

 

First, let’s declare our class.
The objectMaxId variable will be used to generate the next unique filename to link for an object identifier. You could use “filenameFromIdDico.count” but by using another variable you can improve more easily your CacheManager. For example you could allow for removal of objects and still guarantee that you generate a valid unique filename.

 

First of all, here is an utility method that we are going to use to generate a full path from a filename

 

Since Swift does not currently allow class to have static variable, the singleton uses the method of the computed property with a Struct containing a static variable (check this singleton tutorial to learn more about this).
The only difference is that we try to load an existing CacheManager from the phone instead of simply instantiating a new cache manager

 

The init method is used by the NSKeyedUnarchiver.unarchiveObjectWithFile when we reload the CacheManager

 

The encodeWithCoder is used by the NSKeyedArchiver.archiveRootObject to save the CacheManager

 

Now the function to save an object. Of course the objects must either be one of those provided by Apple (Int, String, Array, Dictionnary, …) or one of your object that is NSCoding compliant.

If it’s an object whose ID we do not know, we assign it a unique filename, then we generate the filepath to save it. It’s important to note that we do not track the complete filepath because it contain a unique ID that changes each time you build your app. All this process is done inside a synchronised block for thread safety reasons; we do not want 2 threads to increment the “objectMaxId” field before generating the filename.

Every time we save an object, we save the CacheManager.

 

And finaly the method to load an object from its identifier. If we find it in the dictionnary, we load this object

 

Be sure to download the demo of this cache manager on github !

Partager