self.fetchMin(forStartDate: start, toEndDate: end) { (min, chal) in
guard let mins = min, let challenges = chal else {
return
}
let dict: [Int : [String]] = [mins:challenges]
UserDefaults.standard.set(dict, forKey: "WeekStates")
}
嗨,在上面的程序中,我试图在 userDefaults 中存储键和数组对字符串,但如果我这样做,它会意外崩溃。
如果我尝试使用一个值,它会起作用。
例如:
`let dict: [String] = challenges
UserDefaults.standard.set(dict, forKey: "WeekStates")
Best Answer-推荐答案 strong>
https://developer.apple.com/documentation/foundation/userdefaults
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 , or NSDictionary . 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.
你可以这样做。
let dict: [Int : [String]] = [1:["iOS Dev"]]
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!)
}
关于ios - 尝试在 userDefaults 中存储 Int、arrayof [string] 对时出错,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/44581113/
|