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


当前回答

你可以NSLog你设置的每个值,比如:

NSLog(@"%@",[[NSUserDefaults standardDefaults] stringForKey:@"WhateverTheKeyYouSet"]);

其他回答

在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

在阅读了这个问题的公认答案后,我把这个简单的脚本放在一起,打开iOS模拟器用来存储NSUserDefaults首选项的plist文件,虽然它假设了某种设置(非常适合我的设置),但它可以作为其他人的起点。

$ cat open-prefs-plist.sh
#!/bin/sh

# The project name based on the workspace path, e.g. "MyProject" from "./MyProject.xcworkspace"
WORKSPACE_NAME=$(echo `find . -name *.xcworkspace -type d -exec basename {} \;` | cut -d'.' -f1)
SIMULATOR_PATH="$HOME/Library/Application Support/iPhone Simulator"
# The App's bundle ID taken from its info plist, e.g "com.myproject" from "./MyProject/MyProject-Info.plist"
BUNDLE_ID=`/usr/libexec/PlistBuddy -c Print:CFBundleIdentifier $WORKSPACE_NAME/$WORKSPACE_NAME"-Info.plist"`
# Open all plist files in the simulator path that match the app's bundle ID 
# normally one per iOS version
find "$SIMULATOR_PATH" -name $BUNDLE_ID".plist" -type f -print0 \
    | while IFS= read -r -d '' PLIST; do
    echo $PLIST
    open "$PLIST"
done

例放置:

$ ls -1
MyProject
MyProject Tests
MyProject.xcodeproj
MyProject.xcworkspace
Podfile
open-prefs-plist.sh

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

键:

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

键和值:

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

在模拟器中运行时,我有时会使用下面的代码片段打印出NSUserDefaults文件的位置

NSArray *path = NSSearchPathForDirectoriesInDomains(
   NSLibraryDirectory, NSUserDomainMask, YES);
NSString *folder = [path objectAtIndex:0];
NSLog(@"Your NSUserDefaults are stored in this folder: %@/Preferences", folder);

它生成首选项文件夹的路径

你的NSUserDefaults保存在这个文件夹:/Users/castle/Library/Application Support/iPhone Simulator/User/Applications/BC5056A0-F46B-4AF1-A6DC-3A7DAB984960/Library/Preferences

您的NSUserDefaults文件位于首选项文件夹中,并根据您的前缀和应用程序名称命名。

dk.castleandersen.dreamteam.grid.plist

我希望对于实际的设备也是如此。

很简单,因为plist文件名为<app-bundle-identifier>。Plist,你可以使用find命令找到它的路径。但如果你搜索整台电脑,会花很长时间,所以你必须选择一个好的范围,比如Xcode 6的~/Library/Developer/CoreSimulator。

例子:

查找~/Library/Developer/CoreSimulator -type f -name com.awesome.app.plist

输出将是这样的…

\用户hlung / Library /开发商CoreSimulator / / B61913F6-7D7C-4E45-AE2F-F45220A71823带给您Containers /数据/应用程序/ E4CC51CF-11E5-4168-8A74-6BAE3B89998F / Library / Preferences / com . awesome app。plist

然后你可以使用open命令。或者如果使用iTerm2,只需在路径上单击命令打开它。