有没有办法直接看到什么被保存到NSUserDefaults ?我想看看我的数据保存是否正确。


当前回答

在Swift 2.2中

let path = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)
let folder = path[0]
NSLog("Your NSUserDefaults are stored in this folder: \(folder)/Preferences")

将打印出NSUserDefaults在Xcode调试控制台的plist文件夹位置。复制路径字符串。打开Finder,选择Go菜单项中的“转到文件夹”,粘贴路径字符串。双击plist文件。你会在Xcode编辑器中看到内容。

只能在模拟器中工作

谢谢@Niels Castle

其他回答

寻找名为simholds2的Mac应用程序。它位于菜单栏中,列出你使用过的所有模拟器,然后显示每个应用程序。选择一个,你会得到一个新的Finder窗口,已经打开到应用程序的目录。这使得它超级容易找到你的应用程序和所有的目录。这是一个巨大的时间节省(我愿意捐赠给作者)。

在Swift 4.0中

//func dictionaryRepresentation() -> [String : AnyObject]

因为NSUserDefaults.standardUserDefaults()返回[String: AnyObject]

我们将它转换到NSDictionary中。然后用括号'()'把它括起来将允许我们调用。allkeys或。allvalues就像你在任何NSDictionary上一样

 print((UserDefaults.standard.dictionaryRepresentation() as NSDictionary).allKeys)

我根据Morion的建议构建了这个方法,以便更好地呈现。通过调用[self logAllUserDefaults]使用它

- (void) logAllUserDefaults
{
    NSArray *keys = [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys];
    NSArray *values = [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allValues];
    for (int i = 0; i < keys.count; i++) {
        NSLog(@"%@: %@", [keys objectAtIndex:i], [values objectAtIndex:i]);
    }
}

您可以使用它来获得用户首选项、缓存和许多其他数据的完整路径

print (NSSearchPathForDirectoriesInDomains(。文件目录。

在Swift中,我们可以使用以下功能:-

斯威夫特3。X & 4.x

获取所有键和值:

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

检索用户默认值的完整字典表示:

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

检索密钥:

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

检索值:

我们也可以在这里使用dump,但这将返回values数组中每个元素的完整继承层次结构。如果需要关于对象的更多信息,则使用dump,否则使用正常的print语句。

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

快2.倍

检索用户默认值的完整字典表示:

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

检索密钥:

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

检索值:

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