ios - 将字典保存到 NSUserDefaults Swift
<p><p>我有一个字典,我想将它保存到 NSUserDefaults(或其他东西,以便在我终止应用程序后可以访问我的变量),我找到了一个示例:</p>
<pre><code>var saved = NSUserDefaults.standardUserDefaults()
let dict = ["Name": "Paul", "Country": "UK"]
saved.setObject(dict, forKey: "SavedDict")
</code></pre>
<p>但是当我用它来挖掘字典时,它不起作用。 (可能是因为我的字典有点不一样)</p>
<p>我的字典是这样制作的:</p>
<pre><code> var userDictionary = ()
struct Event {
var sensorName: String
var sensorType: String
var sensorSub: String
}
</code></pre>
<p>我添加这样的元素:</p>
<pre><code>userDictionary = Event(sensorName: "first", sensorType: "Temp", sensorSub: "Third")
</code></pre>
<p>这是我尝试做的,以便我可以存储它。</p>
<pre><code>saved.setObject(userDictionary, forKey: "valueDictionary")
</code></pre>
<p>我得到这个错误:</p>
<blockquote>
<p>Cannot convert value of type '' to expected
argument type 'AnyObject?'</p>
</blockquote>
<p>为了避免这个错误,我这样做了:</p>
<pre><code>self.saved.setObject(self.userDictionary as? AnyObject, forKey: "valueDictionary")
</code></pre>
<p>但我无法检索我保存的内容</p>
<p>不幸的是 <a href="https://stackoverflow.com/questions/2315948/how-to-store-custom-objects-in-nsuserdefaults" rel="noreferrer noopener nofollow">question</a>在一些评论后没有帮助我我相信这里的目标是将我的字典转换为数据(或其他东西),在我检索到它之后我将它转换回字典</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>尝试将数据转换为 NSData,然后像这样检索:</p>
<pre><code>/// Save
NSUserDefaults.standardUserDefaults().setObject(NSKeyedArchiver.archivedDataWithRootObject(object), forKey: key)
/// Read
var data = NSUserDefaults.standardUserDefaults().objectForKey(key) as NSData
var object = NSKeyedUnarchiver.unarchiveObjectWithData(data) as
</code></pre></p>
<p style="font-size: 20px;">关于ios - 将字典保存到 NSUserDefaults Swift,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/38294445/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/38294445/
</a>
</p>
页:
[1]