在UserDefaults中存储数据

时间:2017-10-31 06:57:49

标签: ios swift nsuserdefaults

我正在尝试使用以下方法在UserDefaults中保存用户详细信息,但它会在archiver.encode(assistantContact,forKey: "assistantContact")上崩溃。 我尝试将AssistantContact作为类而不是Struct,但它仍然无效。 如何存档AssistantContact以便将它们保存在用户中?

  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

    }
}

1 个答案:

答案 0 :(得分:0)

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

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