处理Notifications和UserDefaults密钥名称的字符串名称的最常用方法是什么 [英] What is the most common way to handle string names for Notifications and UserDefaults key names

查看:64
本文介绍了处理Notifications和UserDefaults密钥名称的字符串名称的最常用方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将在整个应用程序中使用一些字符串名称作为Notifications和UserDefault名称。

I will be using a few string names throughout my app for my Notifications and UserDefault names.

我听说为了类型安全,定义您的通知名称或 UserDefaults 键名作为静态字符串,并使它们成为类或结构的一部分。

I have heard that for type safety it's a good practice to define your notification names or UserDefaults key names as static strings and make them part of a class or struct.

最常见的处理字符串名的方法是您的Notification和UserDefault名称?

What is the most common way to handle string names for your Notification and UserDefault names?

我曾考虑过将它们作为全局变量放入我的AppDelgate类中,如下所示……

I have thought about putting them in my AppDelgate class as global variables as follow...

let MY_STRING_NAME = "My string name"

class AppDelegate: UIResponder, UIApplicationDelegate {}

/// Then just use MY_STRING_NAME in other classes. 

class SomeClass {
    let myStringName:String = "My string name"
}
/// Then use myClassInstance.myStringName

最好的方法是什么?

推荐答案

一个选项UserDefaults的目的是创建一个帮助程序类,以隐藏您正在使用UserDefaults的事实。这使它在您的其余代码中看起来就像在使用简单的类及其属性一样。

One option for UserDefaults is to create a helper class that hides the fact that you are using UserDefaults. This makes it appear to the rest of your code just like you are using a simple class and its properties.

类似这样的东西:

class MyAppPreferences {
    static let shared = MyAppPreferences()

    private let highScoreKey = "highScore"
    var highScore: Int {
        get {
            return UserDefaults.standard.integer(forKey: highScoreKey)
        }
        set {
            UserDefaults.standard.set(newValue, forKey: highScoreKey)
        }
    }
}

在其他代码上,您可以这样做来设置它:

On other code you can do this to set it:

MyAppPreferences.shared.highScore = 100

或以下内容阅读:

let score = MyAppPreferences.shared.highScore

为应用程序中所需的每个应用程序首选项添加计算的属性和私钥。

Add a computed property and private key for each app preference needed in your app. This makes the rest of your code much cleaner.

由于某种原因,您需要更改将来存储一个或多个首选项的方式,您只需要

And in for some reason you need to change how one or more of the preferences are stored in the future, you only need to change the code in one place.

对于通知名称,您可以在与通知关联的每个类中添加常量。您会在许多iOS类(例如UIApplication,UITextView和其他类)中看到这种模式。

For notification names, you can add constants to each class the notification is associated with. You see this pattern in many iOS classes such as UIApplication, UITextView, and others.

class SomeClass {
    static someClassEventNotification = NSNotification.Name("someUniqueName")
}

这篇关于处理Notifications和UserDefaults密钥名称的字符串名称的最常用方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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