用户默认值是通过nil检查并给我随机字节号


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

" noti"键是零,但仍在通过零检查并打印此:

打印可选(< 62706C69 73743030 D4010203 0405080A 0B542474 6F705824 6F626A65 63747358 247666572 6572D106 0754726F 6F748000 A1095524 6E756C6C 12000186 A05F100F 4E534B65 79656441 72636869 76657208 11161F28 32353A3C 3E4444900 00000000 00010100 00000000 00000C00 00000000 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000来 00005b>)

我不明白为什么它通过nil检查值nil nil nil

打印语句使"noti"键具有值很明显。在这种情况下,它的数据值是:

< 62706C69 73743030 D4010203 0405080A 0B542474 6F705824 6F705824 6F626A65 6374747358 247666572 73696F6E72696E 24 6E756C6C 12000186 A05F100F 4E534B65 79656441 72636869 76657208 11161F28 32353A3A3C 3E44444900 00000000000000000000000000000000000000000000000000000000000000来0000000000来


通常,如果您在检查是否为nil后要使用可选的,则需要使用if let construct

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
}

我尝试了您的代码,但是它成功地跳出了if条件。您确定以前没有添加任何东西吗?

尝试Swift的检查nil

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

如果没有解决,请在if条件之前从UserDefault中删除" Noti"

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

最新更新