Search code examples
iosarraysswiftgetter-setter

Cannot set/get an array of mapped objects to userDefaults on Swift


I've been searching Stack Overflow and no answer could get to what I need to solve this.

I am parsing an array, and retrieving the Data, but I'm stuck trying to set/get it because I need to set it to an NSArray or something before setting it to my userDefaults

Here is my setter/getter:

import Foundation

private extension UserDefaultsKey {
    static var galleryKey: Key<GalleryImage> {
        return "images"
    }
}

class GalleryCache: GalleryCacheType {

    private let userDefault: UserDefaultsServiceType

        var imageUrl: [GalleryImage]? {
        get {
            if let userDefaultValue = self.userDefault.value(forKey: .galleryKey) {
                return userDefaultValue
            }
            return nil
        }
        set {
            if let newValue = newValue {
                let urlData = NSKeyedArchiver.archivedData(withRootObject: newValue)
                userDefault.set(value: urlData, forKey: .galleryKey)
            }
        }
    }

    init() {
        let customUserDefault = UserDefaults(suiteName: "pictures")
        self.userDefault = UserDefaultsService(customUserDefault: customUserDefault)
    }
}

My GalleryCacheType, and UserDefaultServiceType, which are protocols:

protocol GalleryCacheType {

    var imageUrl: [GalleryImage]? { get set }

}

The class implementing UserDefaultProtocols:

import Foundation

final class UserDefaultsService: UserDefaultsServiceType {

    private var customUserDefault: UserDefaults?

    init(customUserDefault: UserDefaults?) {
        self.customUserDefault = customUserDefault
    }

    private var defaults: UserDefaults {
        if let custom = self.customUserDefault {
            return custom
        }
        return UserDefaults.standard
    }

    func value<T>(forKey key: UserDefaultsKey<T>) -> T? {
        return self.defaults.value(forKey: key.key) as? T
    }

    func set<T>(value: T?, forKey key: UserDefaultsKey<T>) {
        self.defaults.set(value, forKey: key.key)
    }
}

And the GalleryImage itself:

import ObjectMapper

struct GalleryImage: Mappable {

    var url: String!

    init?(map: Map) { }

    mutating func mapping(map: Map) {
        url        <- map["file_path"]
    }
}

The errors Xcode is showing me are the following


Solution

  • As stated by @rmdaddy, it's not good to store Data on UserDefaults, so, instead of saving it to UserDefaults, store it on an appropriate sandbox for it (I particularly like Realm).