ios - 尝试在 userDefaults 中存储 Int、arrayof [string] 对时出错
<p><pre><code>self.fetchMin(forStartDate: start, toEndDate: end) { (min, chal) in
guard let mins = min, let challenges = chal else {
return
}
let dict: ]=
UserDefaults.standard.set(dict, forKey: "WeekStates")
}
</code></pre>
<p>嗨,在上面的程序中,我试图在 userDefaults 中存储键和数组对字符串,但如果我这样做,它会意外崩溃。</p>
<p>如果我尝试使用一个值,它会起作用。</p>
<p>例如:</p>
<pre><code>`let dict: =challenges
UserDefaults.standard.set(dict, forKey: "WeekStates")
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><blockquote>
<p><a href="https://developer.apple.com/documentation/foundation/userdefaults" rel="noreferrer noopener nofollow">https://developer.apple.com/documentation/foundation/userdefaults</a></p>
<p>The UserDefaults class provides convenience methods for accessing
common types such as floats, doubles, integers, Booleans, and URLs. A
default object must be a property list—that is, an instance of (or for
collections, a combination of instances of):NSData ,NSString ,
NSNumber ,NSDate ,NSArray , orNSDictionary . If you want to
store any other type of object, you should typically archive it to
create an instance of NSData. For more details, see Preferences and
Settings Programming Guide.</p>
</blockquote>
<p>你可以这样做。</p>
<pre><code>let dict: ]= ]
UserDefaults.standard.set(NSKeyedArchiver.archivedData(withRootObject: dict as NSDictionary) as NSData, forKey: "4WeekStates")
if let unarchivedObject = UserDefaults.standard.object(forKey: "4WeekStates") as? Data {
let dic = NSKeyedUnarchiver.unarchiveObject(with: unarchivedObject as Data) as? NSDictionary
print(dic!)
}
</code></pre></p>
<p style="font-size: 20px;">关于ios - 尝试在 userDefaults 中存储 Int、arrayof 对时出错,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/44581113/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/44581113/
</a>
</p>
页:
[1]