What is the most common way to handle string names for Notifications and UserDefaults key names

只愿长相守 提交于 2019-12-08 06:56:54

问题


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

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.

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

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. 

Or

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

What is the best approach?


回答1:


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.

Something like this:

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

or the following to read it:

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.

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")
}



回答2:


I think using enum is more appropriate way to define constants

User Defaults:

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)
        }
    }
}

Notification:

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)))
} 



回答3:


The common approach is creating

struct Constants { 
   static let key1 = "value1"
   static let key2 = "value2"
   .....
}

// for notifications

extension Notification.Name {
  static let didReceiveData = Notification.Name("didReceiveData")
  static let didCompleteTask = Notification.Name("didCompleteTask")
}

some guys prefer global variables with ( k letter prefix )

let kDomain = "value1"

dates to #define in Objective-C , but using Constants is a clean way to code readers



来源:https://stackoverflow.com/questions/53585412/what-is-the-most-common-way-to-handle-string-names-for-notifications-and-userdef

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