用户默认值是通过零检查并给我随机的字节数

时间:2016-12-21 06:06:46

标签: swift nsuserdefaults

if UserDefaults.standard.object(forKey: "noti") != nil {
    print("print ", UserDefaults.standard.value(forKey: "noti") as Any)
}

“noti”键是零,但它仍然通过零检查并打印出来:

  

print可选(< 62706c69 73743030 d4010203 0405080a 0b542474 6f705824 6f626a65 63747358 24766572 73696f6e 59246172 63686976   6572d106 0754726f 6f748000 a1095524 6e756c6c 12000186 a05f100f   4e534b65 79656441 72636869 76657208 11161f28 32353a3c 3e444900   00000000 00010100 00000000 00000c00 00000000 00000000 00000000   00005b&GT)

我不明白为什么在价值为零时通过零检查

2 个答案:

答案 0 :(得分:2)

print语句显示"noti"键具有值。在这种情况下,它的数据值是:

  

< 62706c69 73743030 d4010203 0405080a 0b542474 6f705824 6f626a65 63747358 24766572 59246172 73696f6e 63686976 6572d106 0754726f 6f748000 a1095524 6e756c6c 12000186 a05f100f 4e534b65 79656441 72636869 76657208 11161f28 32353a3c 3e444900 00000000 00010100 00000000 00000000 00000c00 00000000 00000000 00005b>

通常,如果您在检查它是否为零后使用可选项,则需要使用if let构造

if let noti = UserDefaults.standard.object(forKey: "noti") {
  // Here, noti will be of type Any, rather than Optional<Any>
} else {
  // noti was nil, no need to have any reference to it
}

答案 1 :(得分:0)

我尝试了您的代码,但它已成功跳过if条件。你确定在任何时候都没有添加任何内容。

尝试使用Swift检查nil

的方法
if let noti = UserDefaults.standard.object(forKey: "noti") {
   // 'noti' is available
} else {
   // 'noti' is not available 
}

如果不能解决问题,请尝试删除&#39; noti&#39;来自UserDefault条件之前的if

UserDefault.standard.removeObject(forKey: "noti")

if let noti = UserDefaults.standard.object(forKey: "noti") {
   // 'noti' is available
} else {
   // 'noti' is not available 
}