UserDefaults中的值仅在重新启动后出现

时间:2018-07-24 03:37:22

标签: ios swift codable userdefaults

我将Codable对象和简单String存储在UserDefaults中,并在出现一个使用该值的新屏幕之后。由于某种原因,在我重新启动应用程序之前,可编码对象为零。字符串值立即可用。 为了调试此问题,我尝试通过点击按钮来检索该对象,但是它始终为零,并且在我尝试获取该值时无关紧要。它仅在重启后出现

var user: Contact? = {
    if let contactData = UserDefaults.standard.data(forKey: Constants.UserDefaultsKey.currentUser),
        let contact = try? JSONDecoder().decode(Contact.self, from: contactData) {
        return contact
    }
    return nil
}()

func storeUser(_ user: Contact) {
    do {
        let encodedUser = try JSONEncoder().encode(user)
        UserDefaults.standard.set(encodedUser, forKey: Constants.UserDefaultsKey.currentUser)
        UserDefaults.standard.set(true, forKey: Constants.UserDefaultsKey.isLoggedIn)
        UserDefaults.standard.synchronize()
    } catch {
        print(error.localizedDescription)
    }
}

struct Contact {
    var id: String?
    var email: String?
}

extension Contact: Codable {

enum ContactEncodingKeys: String, CodingKey {
    case id
    case email = "email_address_work"
}

func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: ContactEncodingKeys.self)
    try container.encode(id, forKey: .id)
    try container.encode(email, forKey: .email)
}

init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: ContactEncodingKeys.self)
    id = try container.decode(String.self, forKey: .id)
    email = try container.decode(String?.self, forKey: .email)
}
}

因此user对象为零,直到重新启动为止

1 个答案:

答案 0 :(得分:2)

当前,如果您在设置@RequestMapping(method = RequestMethod.HEAD, value = Constants.KEY ) public ResponseEntity taxonomyPackageExists( @PathVariable final String key ){ // ... return new ResponseEntity(HttpStatus.NO_CONTENT); } 中的对象之前访问user属性,它将仅分配UserDefaults,并且在您创建此类的新对象之前不会再次计算。将nil属性更改为如下计算。

user