注册 登录

清河洛

fyne中的配置及状态存储

qingheluo2024-08-07清河洛309
在fyne中,有两种类型用于存储应用程序的数据,分别为Storage和PreferencesStorage是一种以文件的形式存储在磁盘上的能永久保存的储类型Preferences是一种以键值对的形式保存数据的存储类型StorageStorage是一种以文件的形式存储在磁盘上的能永久保存的储类型可以保存任何格式的文件使用应用程序的Storage()方法获得type Storage interface { RootURI() URI // 存储根目录,无法修改 // 在windows中为:`%APPDATA%/fyne/id/Documents` ...

在fyne中,有两种类型用于存储应用程序的数据,分别为Storage和Preferences

Storage是一种以文件的形式存储在磁盘上的能永久保存的储类型

Preferences是一种以键值对的形式保存数据的存储类型

Storage

Storage是一种以文件的形式存储在磁盘上的能永久保存的储类型

可以保存任何格式的文件

使用应用程序的Storage()方法获得

type Storage interface {
    RootURI() URI
        // 存储根目录,无法修改
        // 在windows中为:`%APPDATA%/fyne/id/Documents`
    Create(name string) (URIWriteCloser, error)
        // 写模式创建一个文件
    Open(name string) (URIReadCloser, error)
        // 读模式打开一个已存在的文件
    Save(name string) (URIWriteCloser, error)
        // 写模式打开一个已存在的文件
    Remove(name string) error
        // 删除一个已存在的文件
    List() []string
        // 列出在根目录中的所有文件名
}

在程序运行时,如果目录%APPDATA%/fyne/id不存在会自动创建,但是Documents目录并不会自动创建

直到通过Create方法创建了文件后才会自动创建并在其中创建指定文件

Preferences

Preferences是一种以键值对的形式保存数据的存储类型

使用应用程序的Preferences()方法获得

Preferences会自动以json格式将所有键值对存储到磁盘中的json文件中

保存文件在windows中为:%APPDATA%/fyne/id/preferences.json

由于Preferences是以json格式存储的,所以为了避免Go和json数据转换时可能的错误,当前版本fyne仅支持键值对中的键为string格式,值为bool、float、int、string格式及这些格式的切片

type Preferences interface {
    Bool(key string) bool
        // 以布尔类型读取指定的key
    BoolWithFallback(key string, fallback bool) bool
        // 以布尔类型读取指定的key,key不存在返回fallback的值
    SetBool(key string, value bool)
        // 设置指定的key值为布尔类型的值

    BoolList(key string) []bool
    BoolListWithFallback(key string, fallback []bool) []bool
    SetBoolList(key string, value []bool)

    Float(key string) float64
    FloatWithFallback(key string, fallback float64) float64
    SetFloat(key string, value float64)

    FloatList(key string) []float64
    FloatListWithFallback(key string, fallback []float64) []float64
    SetFloatList(key string, value []float64)

    Int(key string) int
    IntWithFallback(key string, fallback int) int
    SetInt(key string, value int)

    IntList(key string) []int
    IntListWithFallback(key string, fallback []int) []int
    SetIntList(key string, value []int)

    String(key string) string
    StringWithFallback(key, fallback string) string
    SetString(key string, value string)

    StringList(key string) []string
    StringListWithFallback(key string, fallback []string) []string
    SetStringList(key string, value []string)

    RemoveValue(key string)  // 删除指定的key

    AddChangeListener(func())
        // 监听所有Preferences中存储的键值对
        // 当这些键值对有任何更新时运行指定函数
        // 可以多次运行来设置多个运行函数

    ChangeListeners() []func()
        // 获取所有监听函数
}


网址导航