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


当前回答

你可以打印出应用程序的首选项目录的路径:didFinishLaunchingWithOptions:回调在你的AppDelegate:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    print(FileManager.default.urls(for: .preferencePanesDirectory, in: .userDomainMask).first!)
    return true
}

然后你可以直接查看plist文件,看看里面保存了什么。

其他回答

在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窗口,已经打开到应用程序的目录。这使得它超级容易找到你的应用程序和所有的目录。这是一个巨大的时间节省(我愿意捐赠给作者)。

你可以打印当前所有的NSUserDefaults到日志:

键:

NSLog(@"%@", [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys]);

键和值:

NSLog(@"%@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);

在Swift 4.0中

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

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

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

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

MacOS应用 进入:/Users/{User}/Library/Containers/com。{你的公司}。{your app}/Data/Library/Preferences,然后用Xcode打开你的app的pList。