How to print NSUserDefaults content in Swift

心已入冬 提交于 2020-05-23 04:18:27

问题


How do you print all the content of NSUserDefaults? I need to see everything that has been stored into NSUserDefaults. Is there a simple way to print that or to see it into the logs?

In Swift!

Thank you


回答1:


Taken from - Retrieve UserDefaults in Swift

In Swift we can use the following:-

Swift 3.x & 4.x

For getting all keys & values:

for (key, value) in UserDefaults.standard.dictionaryRepresentation() {
    print("\(key) = \(value) \n")
}

For retrieving the complete dictionary representation of user defaults:

print(Array(UserDefaults.standard.dictionaryRepresentation()))

For retrieving the keys:

// Using dump since the keys are an array of strings.
dump(Array(UserDefaults.standard.dictionaryRepresentation().keys))

For retrieving the values:

We can use dump here as well, but that will return the complete inheritance hierarchy of each element in the values array. If more information about the objects is required, then use dump, else go ahead with the normal print statement.

// dump(Array(UserDefaults.standard.dictionaryRepresentation().values))
print(Array(UserDefaults.standard.dictionaryRepresentation().values))

Swift 2.x

For retrieving the complete dictionary representation of user defaults:

print(NSUserDefaults.standardUserDefaults().dictionaryRepresentation())

For retrieving the keys:

print(NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys.array)

For retrieving the values:

print(NSUserDefaults.standardUserDefaults().dictionaryRepresentation().values.array)



回答2:


for elem in NSUserDefaults.standardUserDefaults().dictionaryRepresentation() {
    println(elem)
}



回答3:


Here is the syntax in to get all standard user defaults in Swift 3

print(UserDefaults.standard().dictionaryRepresentation())



回答4:


With Swift 3.0

print(UserDefaults.standard.dictionaryRepresentation())




回答5:


Here is the syntax that provide more clarity.

let defaults = UserDefaults.standard    
defaults.dictionaryRepresentation().map{print("\($0.key): \($0.value)")}


来源:https://stackoverflow.com/questions/27507213/how-to-print-nsuserdefaults-content-in-swift

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