Creating ImageStore

In Chapter 16, you will have instances of Item write out their properties to a file, which will then be read in when the application starts. However, because images tend to be very large, it is a good idea to keep them separate from other data. You are going to store the pictures the user takes in an instance of a class named ImageStore. The image store will fetch and cache the images as they are needed. It will also be able to flush the cache if the device runs low on memory.

Create a new Swift file named ImageStore. In ImageStore.swift, define the ImageStore class and add a property that is an instance of NSCache.

import Foundation
import UIKit

class ImageStore {

    let cache = NSCache<NSString,UIImage>()

}

The cache works very much like a dictionary (which you saw in Chapter 2). You are able to add, remove, and update values associated with a given key. Unlike a dictionary, the cache will automatically remove objects if the system gets low on memory. While this could be a problem in this chapter (because images will only exist within the cache), you will fix the problem in Chapter 16 when you will also write the images to the filesystem.

Note that the cache is associating an instance of NSString with UIImage. NSString is Objective-C’s version of String. Due to the way NSCache is implemented (it is an Objective-C class, like most of Apple’s classes that you have been working with), it requires you to use NSString instead of String.

Now implement three methods for adding, retrieving, and deleting an image from the dictionary.

class ImageStore {

    let cache = NSCache<NSString,UIImage>()

    func setImage(_ image: UIImage, forKey key: String) {
        cache.setObject(image, forKey: key as NSString)
    }

    func image(forKey key: String) -> UIImage? {
        return cache.object(forKey: key as NSString)
    }

    func deleteImage(forKey key: String) {
        cache.removeObject(forKey: key as NSString)
    }

}

These three methods all take in a key of type String so that the rest of your codebase does not have to think about the underlying implementation of NSCache. You then cast each String to an NSString when passing it to the cache.

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

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