How should I get and set a value of UserDefaults?

落花浮王杯 提交于 2021-02-11 13:00:44

问题


I'm currently developing an application using SwiftUI.

I want to use a UserDefaults value in this app. So I made a code below.

But in this case, when I reboot the app(the 4'th process in the process below), I can't get value from UserDefaults...

  1. Build and Run this project.

  2. Pless the home button and the app goes to the background.

  3. Double-tap the home button and remove the app screen.

  4. press the app icon and reboot the app. Then I want to get value from UserDefaults.

to resolve this problem how should I set and get a value in UserDefaults?


Here is the code:

import SwiftUI

struct ContentView: View {
    
    @State var text = "initialText"
    
    var body: some View {
        VStack {
            Text(text)
            TextField( "", text: $text)
        }.onAppear(){
            if let text = UserDefaults.standard.object(forKey: "text" ){
                self.text = text as! String
            }
        }
        .onDisappear(){
            UserDefaults.standard.set(self.text, forKey: "text")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

ADD

When I add this class following the first answer, that code has a couple of errors like this, is it usual?


Xcode: Version 11.7

Swift: Swift 5


回答1:


Set in a class like this your values: Bool, String(see example), Int, etc...

#if os(iOS)
import UIKit
#else
import AppKit
#endif

import Combine

@propertyWrapper struct UserDefault<T> {

   let key: String
   let defaultValue: T

   init(_ key: String, defaultValue: T) {
       self.key = key
       self.defaultValue = defaultValue
   }

   var wrappedValue: T {
       get {
           return UserDefaults.standard.object(forKey: key) as? T ?? defaultValue
       }
       set {
           UserDefaults.standard.set(newValue, forKey: key)
       }
   }
}

final class UserSettings: ObservableObject {

   let objectWillChange = PassthroughSubject<Void, Never>()

   @UserDefault("myText", defaultValue: "initialText")
   var myText: String {
       willSet { objectWillChange.send() }
   }

}

this to read:

let settings = UserSettings()
let count = settings.countSentence // default countsentence 1

this to update:

let settings = UserSettings()
settings.countSentence = 3 // default countsentence 3

Based on your code:

struct ContentView: View {

let UserDef = UserSettings()
@State var text = ""

var body: some View {
    VStack {
        Text(UserDef.myText)
        TextField("placeholder", text: $text, onCommit: { self.UserDef.myText = self.text})
    }.onAppear() {
        self.text = self.UserDef.myText
    }
}
}


来源:https://stackoverflow.com/questions/63792643/how-should-i-get-and-set-a-value-of-userdefaults

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!