SimpleCacheStore API

Moritz Kanzler edited this page Jan 30, 2017 · 10 revisions

Here is a short overview how to use SimpleCacheStore and which methods are defined. It also shows you some short examples.

Table of Contents

Prepare your objects via NSCoding

If you want to store an object in SimpleCacheStore you have to implement the NSCoding protocol. The following code shows you an example:

import Foundation
import UIKit

class TestObject: NSObject, NSCoding {

    var title: String
    var image: UIImage

    init(title: String, image: UIImage) {
        self.title = title
        self.image = image
    }

    required convenience init?(coder aDecoder: NSCoder) {
        guard let title = aDecoder.decodeObjectForKey("title") as? String,
            let image = aDecoder.decodeObjectForKey("image") as? UIImage
            else {
                return nil
        }

        self.init(title: title, image: image)
    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(self.title, forKey: "title")
        aCoder.encodeObject(self.image, forKey: "image")
    }
}

SimpleCacheStore treat every given object as NSObject, you have to typecast an retrieving object in your app back to the object type you have store it. This flaw you have to keep in mind. Clear defined keys can help you to manage this.

Instance SimpleCacheStore via SCManager

SCManager() //runs SCManager with cache mode .rebuild and cache limit 0
SCManager(cacheMode: CacheMode [.rebuild | ~~.snapshot~~]) //runs SCManager with given CacheMode and cache limit 0
SCManager(cacheMode: CacheMode [.rebuild | ~~.snapshot~~], limit: Int) //runs SCManager with given CacheMode and given cache limit

There are also two contants for the cache mode:

  • Rebuild
  • Snapshot

For further information take a look at the Readme.md

Save objects to SimpleCacheStore

To save objects to SimpleCacheStore just use the save method. It returns a boolean which indicates the success or failure of saving the object.

save(forKey: String, object: NSObject) -> Bool

Once you have instance SCManager you can save your objects into it via:

let scmanager = SCManager(cacheMode: .rebuild, limit: 1000)
if scmanager.save(forKey: "My Identifier", object: TestObject("My Object", image: UIImage(named: "test"))) {
    print("Object saved successfully")
} else {
    print("Saving failed")
}

Save objects with given label

To retrieve multiple objects you can specify them by a label and query them afterwards by this. This is the easiest way to retrieve a range of objects, just like a list of entities. The label is always a String.

To give an object a label you can use an overloaded kind of the save function:

save(forKey: String, object: NSObject, label: String) -> Bool

With an instance of the SCManager you can safe an object with a label as following:

let scmanager = SCManager(cacheMode: .rebuild, limit: 1000)
if scmanager.save(forKey: "My Identifier", object: TestObject("My Object", image: UIImage(named: "test"), label: "friends")) {
    print("Object saved successfully")
} else {
    print("Saving failed")
}

Retrieve objects from SimpleCacheStore

For retrieving objects from SimpleCacheStore just access them via their key. There are two ways two get objects back from SimpleCacheStore. The first runs sequentially and returns the requested object immediately (synchronous). The second way requests the object asynchronously via GCD. With the callback you can react when the object is loading.

Synchronous way

The synchronous way returns the searched object by a given key as an optional.

get(forKey: String) -> NSObject?

Example:

let scmanager = SCManager(cacheMode: .rebuild, limit: 1000)
if let myObject = scmanager.get("My Identifier") as? TestObject {
    print("Object found and retrievied correct")
} else {
    print("Object not found")
}

Asynchronous way

The asynchronous get method searches the object by a given key and uses a callback with a boolean which dedicates the success and the object as an optional. This way helps you to not block the UI when getting objects from SimpleCacheStore.

get(forKey: String, answer: (Bool, NSObject?) -> ())

Example:

let scmanager = SCManager(cacheMode: .rebuild, limit: 1000)
scmanager.get("My Identifier", answer: {
   success, object in
   if let myObject = object as? TestObject {
      print("Object retrieved")
   } else {
      print("Object not found")
   }
})

Retrieve multiple objects from SimpleCacheStore

Once you have specified some objects with a label you can query them with this function:

get(byLabel: String, answer: (Bool, [NSObject]?) -> ())

According to the save example you can retrieve the objects like shown in the next snippet:

let scm = SCManager(cacheMode: .rebuild, limit: 1000)
scm?.get(byLabel: "friends", answer: {
    success, data in
    for friend in data {
      if let obj = friend as! TestObject2 {
        //operate with the object
        print(obj.title)
      }
    }      
})

You will retrieve an (empty) Array of objects or nil if something went wrong.

Delete objects from SimpleCacheStore

To delete an once set object use delete it removes the object for the given key. It returns if the deletion was successfull or an error occurred, either because there is no object for the given key, or there was a problem in core data.

delete(forKey: String) -> Bool

Example:

let scmanager = SCManager(cacheMode: .rebuild, limit: 1000)
if scmanager.delete("My Identifier") {
    print("Object successfully deleted")
} else {
    print("Error, object wasn't deleted")
}

Further methods for managing your SimpleCacheStore instance

Clear all entries in SimpleCacheStore

Is not implemented right at the moment.

Get all objects from SimpleCacheStore

To get all stored objects at once you can use getAll. It will runs on its own thread to not block any other processing. Once all objects are retrieved you can access them via the answer callback. They are stored in an array.

getAll(answer: (Bool, [NSObject]?) -> ())

Example:

let scmanager = SCManager(cacheMode: .rebuild, limit: 1000)
scmanager.getAll({
   success, objects in
   if let myObjects = objects {
      print("Objects retrieved")
   } else {
      print("Error or no objects in storage")
   }
})

Important: This will only works well if you only stored the same type of objects in SimpleCacheStore, or only want to know the size of the stored objects. Think at the typecasting issue!

Clone this wiki locally
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.