iOS Playground中的NSUserDefaults [英] NSUserDefaults in iOS Playground

查看:161
本文介绍了iOS Playground中的NSUserDefaults的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

iOS Playgrounds似乎存在一个奇怪的问题, NSUserDefaults 总是返回 nil 而不是实际值。

There seems to be a strange issue with iOS Playgrounds where NSUserDefaults always returnsnil instead of the actual value.

在iOS Playground中,最后一行错误地返回 nil

In an iOS Playground the last line wrongly returns nil.

import UIKit

let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject("This is a test", forKey: "name")
let readString = defaults.objectForKey("name")

在OSX游乐场最后一行正确返回这是一个测试。

In an OSX Playground the last line correctly returns "This is a test".

import Cocoa

let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject("This is a test", forKey: "name")
let readString = defaults.objectForKey("name")

知道为什么会这样吗? Bug?

Any idea why this is? Bug?

推荐答案

这不是一个真正的bug ..... NSUserDefaults与iOS沙箱环境有关。游乐场不在这种环境中运行。因此,为什么您将无法将文件写入磁盘。如果您在通过模拟器或设备运行时在应用程序中运行此代码,则您将可以访问沙箱环境,NSUserDefaults将返回正确的引用。我确实看到我在游乐场得到了一个适当的参考,并且可以设置和获取值,所以这里必须有其他东西。由于性质原因,我不会依赖于这种方式来测试这种类型的功能。

That's not really a bug..... NSUserDefaults is tied to the iOS sandbox environment. Playgrounds doesn't run in this environment. Hence why you won't be able to write files to disk. If you run this code in the application when running via the simulator or device, you'll have access to the sandbox environment and NSUserDefaults will return a proper reference. I do see though that I get a proper reference in playgrounds and can set and get values, so there has to be something else going on here. I just wouldn't rely on this being the way to test this type of functionality due to the nature.

请注意我同步商店时会发生什么。

Notice what happens when I synchronize the store.

由于没有任何内容可以持续存在,因此该值变为零。

The value becomes nil due to the fact that there's nothing to persist against.

这篇关于iOS Playground中的NSUserDefaults的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆