SwiftUI:什么是@AppStorage属性包装器 [英] SwiftUI: What is @AppStorage property wrapper

查看:442
本文介绍了SwiftUI:什么是@AppStorage属性包装器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾经使用以下语句将重要的App数据(例如登录凭据)保存到UserDefaults中:

I used to save important App data like login credentials into UserDefaults using the following statement:

UserDefaults.standard.set("sample@email.com", forKey: "emailAddress")

现在,我知道SwiftUI引入了新的属性包装器:

Now, I have come to know SwiftUI has introduced new property wrapper called:

@AppStorage

@AppStorage

任何人都可以解释一下新功能的工作原理吗?

Could anyone please explain how the new feature works?

推荐答案

@AppStorage是一种方便的方法,可以从UserDefaults中保存和读取变量,并以与@State属性相同的方式使用它们.可以将其视为@State属性,该属性会自动保存到UserDefaults(并从中读取).

@AppStorage is a convenient way to save and read variables from UserDefaults and use them in the same way as @State properties. It can be seen as a @State property which is automatically saved to (and read from) UserDefaults.

您可以想到以下几点:

@AppStorage("emailAddress") var emailAddress: String = "sample@email.com"

与此等效(在SwiftUI中不允许 且将 not 进行编译):

as an equivalent of this (which is not allowed in SwiftUI and will not compile):

@State var emailAddress: String = "sample@email.com" {
    get {
        UserDefaults.standard.string(forKey: "emailAddress")
    }
    set {
        UserDefaults.standard.set(newValue, forKey: "emailAddress")
    }
}

请注意,@AppStorage的行为类似于@State:对其值的更改将使View无效并重新绘制视图.

Note that @AppStorage behaves like a @State: a change to its value will invalidate and redraw a View.

默认情况下,@AppStorage将使用UserDefaults.standard.但是,您可以指定自己的UserDefaults商店:

By default @AppStorage will use UserDefaults.standard. However, you can specify your own UserDefaults store:

@AppStorage("emailAddress", store: UserDefaults(...)) ...

有用的链接:

  • What is the @AppStorage property wrapper?
  • AppStorage Property Wrapper SwiftUI

这篇关于SwiftUI:什么是@AppStorage属性包装器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆