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 中存储 key 和字符串数组对,但如果这样做,它会意外崩溃。
如果我尝试使用一个值,它就会起作用。
例如:
`let dict: [String] = challenges
UserDefaults.standard.set(dict, forKey: "WeekStates")
最佳答案
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、[string] 对的数组时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44581113/