我将在整个应用程序中使用一些字符串名称作为Notifications和UserDefault名称。
我听说为了类型安全,最好将notification
名称或UserDefaults
键名称定义为静态字符串,并使它们成为类或结构的一部分。
处理Notification和UserDefault名称的字符串名称最常见的方法是什么?
我曾考虑将它们作为全局变量放在我的AppDelgate类中,如下所示。。。
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这一事实。这使得它在代码的其余部分中看起来就像使用一个简单的类及其属性一样。
类似这样的东西:
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)
}
}
}
在其他代码上,你可以这样做来设置它:
MyAppPreferences.shared.highScore = 100
或以下内容读取:
let score = MyAppPreferences.shared.highScore
为应用程序中所需的每个应用程序首选项添加计算属性和私钥。这使得代码的其余部分更加干净。
由于某种原因,您需要在未来更改一个或多个首选项的存储方式,您只需要在一个位置更改代码。
对于通知名称,可以向与通知关联的每个类添加常量。您可以在许多iOS类中看到这种模式,如UIApplication、UITextView和其他类。
class SomeClass {
static someClassEventNotification = NSNotification.Name("someUniqueName")
}
常见的方法是创建
struct Constants {
static let key1 = "value1"
static let key2 = "value2"
.....
}
//用于通知
extension Notification.Name {
static let didReceiveData = Notification.Name("didReceiveData")
static let didCompleteTask = Notification.Name("didCompleteTask")
}
有些人更喜欢带有(k字母前缀(的全局变量
let kDomain = "value1"
可以追溯到Objective-C中的#define
,但使用常量是编写阅读器代码的一种干净方法
我认为使用enum是定义常量的更合适的方式
用户默认值:
class MyAppPreferences {
static let shared = MyAppPreferences()
private enum Key: String {
case userName
case email
}
var userName: String? {
get {
return UserDefaults.standard.string(forKey: Key.userName.rawValue)
}
set {
UserDefaults.standard.set(newValue, forKey: Key.userName.rawValue)
}
}
}
通知:
enum AppNotification: String {
case didReceivedData
case didCompleteTask
}
extension Notification.Name {
init(_ appNotification:AppNotification) {
self.init(appNotification.rawValue)
}
}
//Use:
func notify() {
NotificationCenter.default.post(.init(name: .init(.didReceivedData)))
}