我正在尝试使用以下方法将用户详细信息保存在UserDefaults中,但是它在archiver.encode(assistantContact,forKey: "assistantContact")上崩溃。
我尝试将AssistantContact设置为类而不是Struct,但仍然没有用。
如何也将AssistantContact存档以将其保存在User中?

  struct AssistantContact {
    var firstName: String
    var lastName: String
    var email: [String]
}

struct User {
    var firstName: String
    var lastName: String
    var email: String
    var phoneNumber: String
    var company: String
    var assistantContact: AssistantContact
}

extension User {
    func encode() -> Data {
        let data = NSMutableData()
        let archiver = NSKeyedArchiver(forWritingWith: data)
        archiver.encode(firstName, forKey: "firstName")
        archiver.encode(lastName, forKey: "lastName")
        archiver.encode(email, forKey: "email")
        archiver.encode(phoneNumber, forKey: "phoneNumber")
        archiver.encode(company, forKey: "company")
        archiver.encode(assistantContact, forKey: "assistantContact")
        archiver.finishEncoding()
        return data as Data
    }

    init?(data: Data) {
        let unarchiver = NSKeyedUnarchiver(forReadingWith: data)
        defer {
            unarchiver.finishDecoding()
        }
        guard let firstName = unarchiver.decodeObject(forKey: "firstName") as? String else { return nil }
        guard let lastName = unarchiver.decodeObject(forKey: "lastName") as? String else { return nil }
        guard let email = unarchiver.decodeObject(forKey: "email") as? String else { return nil }
        guard let phoneNumber = unarchiver.decodeObject(forKey: "phoneNumber") as? String else { return nil }
        guard let company = unarchiver.decodeObject(forKey: "company") as? String else { return nil }
        guard let assistantContact = unarchiver.decodeObject(forKey: "assistantContact") as? AssistantContact else { return nil }
        self.firstName = firstName
        self.lastName = lastName
        self.email = email
        self.phoneNumber = phoneNumber
        self.company = company
        self.assistantContact = assistantContact

    }
}

最佳答案

您可以将值存储在NSObject中,然后使用此方法来归档数据。
archiver.encode(assistantContact, forKey: "assistantContact")替换为archiver.archivedData(withRootObject: assistantContact)

并将其用于取消存档的unarchiver.unarchiveObject(with: assistantContact)

10-08 12:26