Attempt to insert non-property list object when trying to save a custom object in Swift 3

后端 未结 5 1702
北海茫月
北海茫月 2020-11-27 14:58

I have a simple object which conforms to the NSCoding protocol.

import Foundation

class JobCategory: NSObject, NSCoding {
    var id: Int
    v         


        
相关标签:
5条回答
  • 2020-11-27 15:18

    Save dictionary Into userdefault

    let data = NSKeyedArchiver.archivedData(withRootObject: DictionaryData)
    UserDefaults.standard.set(data, forKey: kUserData)
    

    Retrieving the dictionary

    let outData = UserDefaults.standard.data(forKey: kUserData)
    let dict = NSKeyedUnarchiver.unarchiveObject(with: outData!) as! NSDictionary
    
    0 讨论(0)
  • 2020-11-27 15:23

    Update Swift 4, Xcode 10

    I have written a struct around it for easy access.

    //set, get & remove User own profile in cache
    struct UserProfileCache {
        static let key = "userProfileCache"
        static func save(_ value: Profile!) {
             UserDefaults.standard.set(try? PropertyListEncoder().encode(value), forKey: key)
        }
        static func get() -> Profile! {
            var userData: Profile!
            if let data = UserDefaults.standard.value(forKey: key) as? Data {
                userData = try? PropertyListDecoder().decode(Profile.self, from: data)
                return userData!
            } else {
                return userData
            }
        }
        static func remove() {
            UserDefaults.standard.removeObject(forKey: key)
        }
    }
    

    Profile is a Json encoded object.

    struct Profile: Codable {
    let id: Int!
    let firstName: String
    let dob: String!
    }
    

    Usage:

    //save details in user defaults...
    UserProfileCache.save(profileDetails)
    

    Hope that helps!!!

    Thanks

    0 讨论(0)
  • 2020-11-27 15:24

    Based on Harjot Singh answer. I've used like this:

    struct AppData {
    
        static var myObject: MyObject? {
    
            get {
                if UserDefaults.standard.object(forKey: "UserLocationKey") != nil {
                    if let data = UserDefaults.standard.value(forKey: "UserLocationKey") as? Data {
                        let myObject = try? PropertyListDecoder().decode(MyObject.self, from: data)
                        return myObject!
                    }
                }
                return nil
            }
    
            set {
                UserDefaults.standard.set(try? PropertyListEncoder().encode(newValue), forKey: "UserLocationKey")
            }
    
        }
    }
    
    0 讨论(0)
  • 2020-11-27 15:30

    You need to create Data instance from your JobCategory instance using NSKeyedArchiver.archivedData(withRootObject:) and store that Data instance in UserDefaults and later unarchive using NSKeyedUnarchiver.unarchiveObject(with:), So try like this.

    For Storing data in UserDefaults

    let category = JobCategory(id: 1, name: "Test Category", URLString: "http://www.example-job.com")
    let encodedData = NSKeyedArchiver.archivedData(withRootObject: category, requiringSecureCoding: false)
    let userDefaults = UserDefaults.standard
    userDefaults.set(encodedData, forKey: UserDefaultsKeys.jobCategory.rawValue)
    

    For retrieving data from UserDefaults

    let decoded  = UserDefaults.standard.object(forKey: UserDefaultsKeys.jobCategory.rawValue) as! Data
    let decodedTeams = NSKeyedUnarchiver.unarchiveObject(with: decoded) as! JobCategory
    print(decodedTeams.name)
    
    0 讨论(0)
  • 2020-11-27 15:37

    Swift save Codable object to UserDefault with @propertyWrapper

    @propertyWrapper
        struct UserDefault<T: Codable> {
            let key: String
            let defaultValue: T
    
            init(_ key: String, defaultValue: T) {
                self.key = key
                self.defaultValue = defaultValue
            }
    
            var wrappedValue: T {
                get {
    
                    if let data = UserDefaults.standard.object(forKey: key) as? Data,
                        let user = try? JSONDecoder().decode(T.self, from: data) {
                        return user
    
                    }
    
                    return  defaultValue
                }
                set {
                    if let encoded = try? JSONEncoder().encode(newValue) {
                        UserDefaults.standard.set(encoded, forKey: key)
                    }
                }
            }
        }
    
    
    
    
    enum GlobalSettings {
    
        @UserDefault("user", defaultValue: User(name:"",pass:"")) static var user: User
    }
    

    Example User model confirm Codable

    struct User:Codable {
        let name:String
        let pass:String
    }
    

    How to use it

    //Set value 
     GlobalSettings.user = User(name: "Ahmed", pass: "Ahmed")
    
    //GetValue
    print(GlobalSettings.user)
    
    0 讨论(0)
提交回复
热议问题