NSUserDefaults数据持久化

import UIKit

class ViewController3: UIViewController {

    let defaults = UserDefaults.standard
    
    var dataSource = [String]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        
        let label = UILabel()
        
        label.frame = CGRect(x: 100, y: 100, width: 100, height: 50)
        label.backgroundColor = UIColor.red
        
//        userDefaultSet(string: "PEIDUO")
        
        let array =  userDefaultGet()
        
        label.text = array.first
        
        view.addSubview(label)
    }
    
    func userDefaultSet(string : String){
        
        dataSource.append(string)
        
        defaults.set( dataSource, forKey:"dataSource" )
    }
    
    func userDefaultGet() -> [String]{
        
        guard defaults.array(forKey: "dataSource") == nil else {
            let array = defaults.array(forKey: "dataSource") as! [String]
            return array
        }
        
        return [String]()
    }

这就是一段用NSUserDefaults数据持久化完成的一段操作.

你可能感兴趣的:(NSUserDefaults数据持久化)