gpt4 book ai didi

ios - 在展开可选内容时,将 Parse PFUser 信息快速加载到 View 中失败,并发现 nil

转载 作者:行者123 更新时间:2023-11-30 14:06:22 25 4
gpt4 key购买 nike

我在这件事上浪费了太多时间。也许这就是为什么我看不到问题所在。

我正在将 PFUser 数据从 Parse 加载到 View 中,以便可以对其进行编辑等。

在解包一个我知道有值的可选值时,我的代码的这一部分不断崩溃,意外发现 nil。

func loadUser() {
// var currentUser = PFUser.currentUser()

println(currentUser)

//currentUser = nil

if currentUser != nil {


if let userImageView = currentUser?["picture"] as? PFFile {
userImageView.getDataInBackgroundWithBlock {(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
if let imageData = imageData {
let image = UIImage(data:imageData)
}
}
}
}

if let currentUser = currentUser {

var userName: AnyObject? = currentUser["username"]

println(userName)
// if let currentUser = currentUser {
self.nameField.text = userName as! String
// }
}
}
}

println(currentUser) 和 println(userName) 都有值并显示在我的控制台上。

最佳答案

虽然看起来不太可能,但您的 currentUser 变量可能会从您脚下被释放 - 为什么不从一开始就使用条件赋值:

if let currentUser = currentUser {

if let userImageView = currentUser["picture"] as? PFFile {
userImageView.getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) -> Void in
if error == nil {
if let imageData = imageData {
if let image = UIImage(data:imageData) {
// do whatever you want to do with your image
}
}
}
}
}
if let userName: String = currentUser["username"] as? String {
println(userName)
self.nameField.text = userName
}
}

鉴于您所说的崩溃位置,您的 currentUser 对象似乎更有可能具有 nil userName 属性(或一个这不是一个字符串

此外,UIImage(data: NSData) 返回一个可选值,因此如果您尝试使用它,它可能是nil(并且,具体取决于您所使用的库)使用时,它可能被声明为隐式解包的可选)。

由于这些类型的错误,我通常会避免像瘟疫这样的隐式解包选项 - 如果您始终使用条件赋值而不是检查 nil,然后尝试使用该变量作为隐式解包选项,那么这种情况就不会发生。

关于ios - 在展开可选内容时,将 Parse PFUser 信息快速加载到 View 中失败,并发现 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32336475/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com