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


当前回答

您可以检查数组中由返回的每个键的值

[[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys]

其他回答

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

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

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

在模拟器中运行时,我有时会使用下面的代码片段打印出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

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

您可以检查数组中由返回的每个键的值

[[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys]

在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

对于希望找到存储在模拟器中的首选项的新位置的用户。 这是我找到存储值的地方。

/Users/vikas/Library/Developer/CoreSimulator/Devices/CE5A0444-BD98-4FEE-A839-92728D6E9895/data/Containers/Data/Application/F7430839-ED2C-408A-8A8E-FE7FFAABA8E2/Library/Preferences

因为我们可以看到有很大的标识符,很难从终端猜出来,所以我建议在终端或finder中搜索它们。

文件名应该以{bundle id}结尾。Plist,例如com.sellerbuddy.online.plist,这样你就可以直接进入终端,输入你的应用程序包标识符。

find ~/Library/Developer/CoreSimulator/Devices -type f -name "com.sellerbuddy.online.plist"