allenlinli allenlinli - 5 months ago 18
iOS Question

What's the disadvantage of saving image to NSUserDefault?

What's the disadvantage of saving images to NSUserDefault?
Why is it not the best practice to do that?

Sorry about that I don't provide code here.


NSUserDefaults is explicitly meant for storing user defaults – images don't belong there especially because NSUserDefaults writes information into a .plist file. Raw image data does not belong into .plist files. Apart from that, it is also not very efficient: the more information you store in a .plist file, the longer it takes to load it. If you want to load a specific image, you would have to load the entire .plist file – including all the other images you don't need at the moment. Briefly speaking: don't do it.

A more appropriate and also more efficient approach for storing your images would be to store them in your application's documents directory – where they belong to.

You could do that like this:

Storing your image

func saveImage(image: UIImage, fileName: String) {
        let documentsDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]

        do {
            try UIImagePNGRepresentation(image)?.write(to: URL(string: documentsDirectory)!, options: .atomicWrite)
        } catch {
            // Handle possible errors here

Calling your saveImage function

let theImage = UIImage(named: "yourImage")
let documentsDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
self.saveImage(image: theImage!, fileName: "yourImageName")