Store [String] in NSUserDefaults

前端 未结 5 1069
南方客
南方客 2020-11-27 17:35

I want to save a Swift Style String Array into NSUserDefaults, but acutally the \"if\" statement in the code says that returnValue is always nil.

Later in the code (

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

    As stated in the documentation:

    For NSArray and NSDictionary objects, their contents must be property list objects.

    This means you need to convert your String objects to NSString when saving, something like this should work:

    var food : [String] {
        get {
            var returnValue : [String]? = NSUserDefaults.standardUserDefaults().objectForKey("food") as? [String]
            if returnValue == nil      //Check for first run of app
            {
                returnValue = ["muesli", "banana"]; //Default value
            }
            return returnValue!
        }
        set (newValue) {
            //  Each item in newValue is now a NSString
            let val = newValue as [NSString]
            NSUserDefaults.standardUserDefaults().setObject(val, forKey: "food")
            NSUserDefaults.standardUserDefaults().synchronize()
        }
    }
    
    0 讨论(0)
  • 2020-11-27 18:20

    In Swift 3.0

    Store

    UserDefaults.standard.set(newValue, forKey: "yourkey")
    UserDefaults.standard.synchronize()
    

    Retrieve

    var returnValue: [NSString]? = UserDefaults.standard.object(forKey: "yourkey") as? [NSString]
    

    Remove

    UserDefaults.standard.removeObject(forKey: "yourkey")
    

    Reference: NSUserdefault objectTypes

    0 讨论(0)
  • 2020-11-27 18:25

    //

        class func saveCustomObject(_ object: AnyObject?, key: String) { 
          let encodedObject = NSKeyedArchiver.archivedData(withRootObject: object!) 
          let userDefaults = UserDefaults.standard userDefaults.set(encodedObject, forKey: key) 
          userDefaults.synchronize() 
        } 
    

    //

    class func loadCustomObject(_ key: String) -> AnyObject? { 
       let userDefaults = UserDefaults.standard 
       if let userDefaultKey = userDefaults.object(forKey: key) { 
         let encodedObject = userDefaultKey as! NSData 
         return NSKeyedUnarchiver.unarchiveObject(with: encodedObject as Data)! as AnyObject? 
       } else {
         return nil 
       }
    } 
    

    //

    class func removeCustomObject(_ key: String) { // 
        let encodedObject = NSKeyedArchiver.archivedDataWithRootObject(object!) let userDefaults = 
        UserDefaults.standard userDefaults.removeObject(forKey: key) 
        userDefaults.synchronize()
     }
    

    call Method

    let aParams : [String : String] = [ "DeviceType" : "iOS", ]
    CommonMethods.saveCustomObject(aParams as AnyObject?, key:Constants.kLoginData)
    

    0 讨论(0)
  • 2020-11-27 18:29

    The following code should help you resolve your problem:

    import UIKit
    
    class ViewController: UIViewController {
    
        var food: [String] {
            get {
                if let returnValue = NSUserDefaults.standardUserDefaults().objectForKey("food") as? [String] {
                    return returnValue
                } else {
                    return ["muesli", "banana"] //Default value
                }
            }
            set {
                NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: "food")
                NSUserDefaults.standardUserDefaults().synchronize()
            }
        }
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            print(food) // prints: ["muesli", "banana"] (at first launch)
    
            food = ["cake"]
            print(food) // prints: ["cake"]
    
            food += ["spaghetti"]
            print(food) // prints: ["cake", "spaghetti"]
    
            food = []
            print(food) // prints: []
    
            NSUserDefaults.standardUserDefaults().setObject(nil, forKey: "food")
            print(food) // prints: ["muesli", "banana"]
        }
    
    }
    

    However, with the previous code, if you set food = [], you will have a problem as food won't return ["muesli", "banana"]. In order to avoid this, you may prefer the following code:

    import UIKit
    
    class ViewController: UIViewController {
    
        var food: [String] {
            get {
                if let returnValue = NSUserDefaults.standardUserDefaults().objectForKey("food") as? [String] {
                    return returnValue == [] ? ["muesli", "banana"] : returnValue
                } else {
                    return ["muesli", "banana"] //Default value
                }
            }
            set {
                NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: "food")
                NSUserDefaults.standardUserDefaults().synchronize()
            }
        }
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            print(food) // prints: ["muesli", "banana"] (at first launch)
    
            food = ["cake"]
            print(food) // prints: ["cake"]
    
            food += ["spaghetti"]
            print(food) // prints: ["cake", "spaghetti"]
    
            food = []
            print(food) // prints: ["muesli", "banana"]
    
            NSUserDefaults.standardUserDefaults().setObject(nil, forKey: "food")
            print(food) // prints: ["muesli", "banana"]
        }
    
    }
    
    0 讨论(0)
  • 2020-11-27 18:36

    Set and Get NSUserDefault with function

    Use below function to globally use , declare in any class any use in whole app

    Declaration

    func setUserDefault(ObjectToSave : AnyObject?  , KeyToSave : String)
    {
        let defaults = NSUserDefaults.standardUserDefaults()
    
        if (ObjectToSave != nil)
        {
    
            defaults.setObject(ObjectToSave, forKey: KeyToSave)
        }
    
        NSUserDefaults.standardUserDefaults().synchronize()
    }
    
    func getUserDefault(KeyToReturnValye : String) -> AnyObject?
    {
        let defaults = NSUserDefaults.standardUserDefaults()
    
        if let name = defaults.valueForKey(KeyToReturnValye)
        {
            return name
        }
        return nil
    }
    

    How to call

    Classname_where_this_function_declare.sharedInstance.setUserDefault("value", KeyToSave: "key")**  
    
    0 讨论(0)
提交回复
热议问题