class UserData: NSObject, NSCoding, ObservableObject {
// MARK:- Properties
@Published var assignments: [Assignment]
@Published var courses: [Course] = []
@Published var username: String = ""
@Published var appState: AppState = AppState(willPresentSplashScreen: false)
...
// MARK:- NSCoding
func encode(with coder: NSCoder) {
coder.encode(assignments, forKey: PropertyKey.assignments)
coder.encode(courses, forKey: PropertyKey.courses)
coder.encode(username, forKey: PropertyKey.username)
coder.encode(appState, forKey: PropertyKey.appState)
}
required convenience init?(coder decoder: NSCoder) {
let assignments = decoder.decodeObject(forKey: PropertyKey.assignments) as? [Assignment]
let courses = decoder.decodeObject(forKey: PropertyKey.courses) as? [Course]
let username = decoder.decodeObject(forKey: PropertyKey.username) as? String
let appState = decoder.decodeObject(forKey: PropertyKey.appState) as? AppState
self.init(assignments: assignments, courses: courses, username: username, appState: appState)
}
}
我对应用程序开发还比较陌生,正在尝试为使用SwiftUI编写的作业管理应用程序增加持久性。我在“ UserData”类中实现了NSCoding,并且能够创建...
init(assignments: [Assignment], courses: [Course], username: String, appState: AppState) {
self.assignments = assignments
self.courses = courses
self.username = username
self.appState = appState
}
这将给您一个错误,因为您有可选参数,并且初始化程序不希望有可选参数,所以您需要解包从init?(coder decoder: NSCoder)
传递来的参数。
init?(coder decoder: NSCoder)
是失败的初始化程序,因此如果一切都不正确,则可以返回nil
:
required convenience init?(coder decoder: NSCoder) { guard let assignments = decoder.decodeObject(forKey: PropertyKey.assignments) as? [Assignment], let courses = decoder.decodeObject(forKey: PropertyKey.courses) as? [Course], let username = decoder.decodeObject(forKey: PropertyKey.username) as? String, let appState = decoder.decodeObject(forKey: PropertyKey.appState) as? AppState else { return nil } self.init(assignments: assignments, courses: courses, username: username, appState: appState) }
我可能会摆脱分配给
courses
,username
和appState
的默认值-您不需要它们,因为这些值将来自初始化程序