Application Data Caching in iOS

Cache is a prominent term which you’ve heard very often in Computing world. Alike, we have cache memory in our iPhones.

As per the Wikipedia, description of cache is

“Cache Memory is a fast and relatively small memory that is completely handled by the hardware, that stores the most recently used  main memory (RAM). The function of the cache memory is to speed up the RAM data access (performance increasing).

Every Smartphone OS like Android or iOS allow developer to cache their data in Cache Memory. Internally, cache Memory is handled by OS itself and they can clear app-cache when OS is in shortage of cache memory. So, it’s quite unreliable to store data in cache memory but you can use it to store data for a particular active session.

Assumption

Say, i have three View Controllers (A, B and C) and i have typed some name in A View controller. Then, I navigate to Viewcontroller-B and them moved to C. In C View Controller, I need what you have typed in  View Controller-A. In such cases, you should maintain a global property which you can access from any screen. That particular file is CacheManager which will handle all the global property which store the instance or value.

 

So it would be like:

When I was typing name in text field of View Controller-A then, at that point of time I will store the inputted name in a Global Property (i.e Cache) which you can access it from View Controller-C.

Basically, In Step (1) we are saving the ‘name’ text field value and then, in Step (2) we are trying to retrieve data what we’ve cached. Cache Data retains their data till application’s active session. It will loose it’s state when you kill your app. So, every time when you launch your app you‘ll have new cache.

Customize Your Cache Manager

You are going to maintain a CacheManager file in your project which is a singleton class with list of properties.

For instance, I want to cache my name then, I’ll declare a property with String-Optional type.

var userName:String?

And, after every declaration make sure you put your property to nil in clear() method. As, we will use this method to clear cache when we want to de-initialise all the property.

userName = nil

Demonstration

I assume you have enough skills to design a screen. So, there is a View Controller which list two Text Fields (which accepts Name and Account Number) along with three buttons (Add to Cache, Get From Cache and Clear Cache).

Last, we need a Label where you can show your cached data.

picture2

Next, we will create outlets for text fields & label and touch up connection for buttons.

Next, we will modify CacheManager as per our need. For time being, we want to cache employee name and employee number what user is passing. So, we will declare two Optional-String type properties.

Then Our Cache Manager would be like:

//MARK:- Stored Property for  Username(String)
var employeeName:String?

  //MARK:- Stored Property for Account Number (String)
  var employeeID:String?

//MARK:- Computed Property for User Age
    //Special Case : I want to restrict user to have their AGE to '18'. They can't allow you to have their age more than 18.
    var employeeRating:Int?{
        
        didSet{
            if employeeRating! > 10{
                employeeRating = 10
            }
        }
        
    }
  
 //MARK: Clear Cache
    public func clear(){
        
        employeeName = nil
        employeeID = nil
        employeeRating = 0


    }

1. Write Data to Cache

Now, we are ready with our CacheManager and now we will store corresponding value when you click on button “Add to Cache”.

private func cacheData(employeeName:String, employeeID:String, employeeRating:String){
    
        
        //Employee Name
        CacheManager.shared.employeeName = employeeName
        
        //Employee ID
        CacheManager.shared.employeeID = employeeID
        
        //Rating
        CacheManager.shared.employeeRating = Int(employeeRating) ?? 0

CacheManager is a singleton class which force you to use only single instance of cachemanager object. Hence, we have a shared object which return you only instance of CacheManager across the app.

That’s the sole reason we are using CacheManager.shared

CacheData() is a private method which is called from buttonCacheData_Clicked(_:) along with the three parameters.

self.cacheData(employeeName: self.textFieldEmployeeName.text!, employeeID: self.textFieldEmployeeId.text!, employeeRating: self.textFieldRatting.text!)

Here, we are passing the text field’s value to the cacheData() method which ultimately store data in cache object.

2. Read Data From Cache

 

Next, we will see how to retrieve data from Cache.

Alike, every property getter we’ll call by its name. So, we will write something like this:

let cacheEmployeeID = CacheManager.shared.employeeID ?? ""
let cacheEmpolyeeName = CacheManager.shared.employeeName ?? ""
let cacheEmployeeRating = CacheManager.shared.employeeRating ?? 0

Note : ?? operator checks if the corresponding value is nil then it will set the “empty”.

Since, properties are Optional type so we have to check whether it is returning nil value or not.

If it’s a nil value then store “ ” else return its value. That’s the sole reason to use “nil-coalescing operator (??)”.

3. Clear Cache

What if, i want to clear all data what i have cache. Then, you just call a method i.e. clear()

CacheManager.shared.clear()

picture4

Conclusion

CacheManager allow you to store state of any object or any value which you want to use in further screen of your app. Caching is only feasible when you don’t to persist your data permanently. As, it will reset its value when app restart itself. It come up with the best practice to maintain a Cache when you storing state for a single active-session of App.

 

 

Leave a Reply