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 is 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 documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let path = documentsURL?.appendingPathComponent(fileName)
do {
try UIImagePNGRepresentation(image)?.write(to: path!)
} catch {
// Handle possible errors here
print(error.localizedDescription)
}
}
Calling your saveImage
function
let theImage = UIImage(named: "yourImage")
saveImage(image: theImage!, fileName: "yourImageName")
After storing your images to your application's documents directory, you could take your image's file path and store it in your CoreData database for retrieving the image later.
CoreData can also automate this for you with a little trick. By enabling the "Allows External Storage" checkbox for your binary data attribute, CoreData will store the image somewhere on your device and will only keep a reference to the image in your database (rather than the actual image), in order to keep the performance high. Here's some more information about that.