kabochappinote

articlesswift
UserDefaults

UserDefaults


2021-08-30 11:33:28
   import UIKit
    let defaults = UserDefaults.standard

    // Float
    defaults.set(0.24, forKey: "Volume")
    let volume = defaults.float(forKey: "Volume")

    // Bool
    defaults.set(true, forKey: "MusicOn")

    // Any
    defaults.set("kabo", forKey: "PlayerName")
    defaults.set(Date(), forKey: "AppLastOpenedByUser")
    let appLastOpen = defaults.object(forKey: "AppLastOpenedByUser")

    // Array
    let array = [1, 2, 3]
    defaults.set(array, forKey: "myArray")
    let myArray = defaults.array(forKey: "myArray") as! [Int]
    print(myArray[0])


    let dictionaryKey = "myDictionary"
    let dictionary = ["name": "kabo"]
    defaults.set(dictionary, forKey: dictionaryKey)
    let myDictionary = defaults.dictionary(forKey: dictionaryKey)
    print(myDictionary!["name"]!)

   class ViewController: UIViewController {

    private var itemArray = ["Find Mike"]
    private let defaults = UserDefaults.standard

    override func viewDidLoad() {
        super.viewDidLoad()
        if let items = defaults.array(forKey: "TodoListArray") as? [String] {
            itemArray = items
        }
    }

    func addTapped() {
        self.itemArray.append(textField.text!)
        self.defaults.setValue(self.itemArray, forKey: "TodoListArray")
        self.tableView.reloadData()
    }
}

// MARK: - TableViewDataSource
extension ViewController: UITableViewDataSource {
    // number of cell
    func tableView(_ tableView: UITableView,
                   numberOfRowsInSection section: Int) -> Int {
        return itemArray.count
    }
    // setting cell
    func tableView(_ tableView: UITableView,
                   cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(
                         withIdentifier: "ToDoItemCell", for: indexPath)
        cell.textLabel?.text = "\(itemArray[indexPath.row])"
        return cell
    }
}
   

※ 起動時の音量設定等の小さな値のデータ保存に使用

   
func application(_ application: UIApplication, 
                   didFinishLaunchingWithOptions launchOptions: 
                   [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

// UserDefaultsの保存場所 Path/Library/Preferences/***.plist
   print("Path: \(NSSearchPathForDirectoriesInDomains(
         .documentDirectory, .userDomainMask, true).last! as String)")
}

back