gpt4 book ai didi

swift - fatal error : unexpectedly found nil while unwrapping an Optional value. Swift

转载 作者:行者123 更新时间:2023-11-28 06:50:45 25 4
gpt4 key购买 nike

我是 Swift 的新手。我的问题是我不确定如何展开可选值。当我打印 object.objectForKey("profile_picture") 时,我可以看到 Optional(<PFFile: 0x7fb3fd8344d0>) .

    let userQuery = PFUser.query()
//first_name is unique in Parse. So, I expect there is only 1 object I can find.
userQuery?.whereKey("first_name", equalTo: currentUser)
userQuery?.findObjectsInBackgroundWithBlock({ (objects: [PFObject]?, error: NSError?) -> Void in
if error != nil {
}
for object in objects! {
if object.objectForKey("profile_picture") != nil {
print(object.objectForKey("profile_picture"))
self.userProfilePicture.image = UIImage(data: object.objectForKey("profile_pricture")! as! NSData)
}
}
})

最佳答案

您将使用 if let 来执行“可选绑定(bind)”,仅当相关结果不是 nil 时才执行 block (并绑定(bind)变量 profilePicture 到进程中的解包值)。

它会是这样的:

userQuery?.findObjectsInBackgroundWithBlock { objects, error in
guard error == nil && objects != nil else {
print(error)
return
}
for object in objects! {
if let profilePicture = object.objectForKey("profile_picture") as? PFFile {
print(profilePicture)
do {
let data = try profilePicture.getData()
self.userProfilePicture.image = UIImage(data: data)
} catch let imageDataError {
print(imageDataError)
}
}
}
}

或者,如果你想异步获取数据,也许:

userQuery?.findObjectsInBackgroundWithBlock { objects, error in
guard error == nil && objects != nil else {
print(error)
return
}
for object in objects! {
if let profilePicture = object.objectForKey("profile_picture") as? PFFile {
profilePicture.getDataInBackgroundWithBlock { data, error in
guard data != nil && error == nil else {
print(error)
return
}
self.userProfilePicture.image = UIImage(data: data!)
}
}
}
}

这将是沿着这些思路的东西,使用 if let 来解包那个可选的。然后您必须获取与 PFFile 对象关联的 NSData(来自 getData 方法或 getDataInBackgroundWithBlock,大概)。

参见 Optional Binding The Swift Programming Language 中的讨论。

关于swift - fatal error : unexpectedly found nil while unwrapping an Optional value. Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34982999/

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