How to save NSMutablearray in NSUserDefaults

前端 未结 9 1179
盖世英雄少女心
盖世英雄少女心 2020-11-29 17:50

I have two NSMutableArray\'s. They consist of images or text. The arrays are displayed via a UITableView. When I kill the app the data within the <

9条回答
  •  悲哀的现实
    2020-11-29 17:55

    In Swift 3, for an NSMutableArray, you will need to encode/decode your array to be able to save it/ retrieve it in NSUserDefaults :

    Saving

    //Encoding array
    let encodedArray : NSData = NSKeyedArchiver.archivedData(withRootObject: myMutableArray) as NSData
    
    //Saving
    let defaults = UserDefaults.standard
    defaults.setValue(encodedArray, forKey:"myKey")
    defaults.synchronize()
    

    Retrieving

    //Getting user defaults
    let defaults = UserDefaults.standard
    
    //Checking if the data exists
    if defaults.data(forKey: "myKey") != nil {
       //Getting Encoded Array
       let encodedArray = defaults.data(forKey: "myKey")
    
       //Decoding the Array
       let decodedArray = NSKeyedUnarchiver.unarchiveObject(with: encodedArray!) as! [String]
    }
    

    Removing

    //Getting user defaults
    let defaults = UserDefaults.standard
    
    //Checking if the data exists
    if defaults.data(forKey: "myKey") != nil {
    
        //Removing the Data
        defaults.removeObject(forKey: "myKey")
    
    }
    

提交回复
热议问题