【问题标题】:fatal error: unexpectedly found nil while unwrapping an Optional value. Swift致命错误:在展开可选值时意外发现 nil。迅速
【发布时间】:2016-01-24 23:43:28
【问题描述】:

我是 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)
            }
        }
    })

【问题讨论】:

    标签: swift parse-platform fatal-error optional unwrap


    【解决方案1】:

    您将使用if let 执行“可选绑定”,仅当相关结果不是nil 时才执行块(并将变量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)。

    请参阅Swift 编程语言中的Optional Binding 讨论。

    【讨论】:

    • 它有效。你介意解释一下“如果让”是什么吗?
    • if let 是“可选绑定”,即仅当相关结果不是nil 时才执行块(并将变量profilePicture 绑定到进程中的未包装值)。显然,如果对象是nil,它就会跳过if let 块。请参阅 Swift 编程语言中的 Optional Binding
    • 好的。知道了。谢谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-26
    • 2015-10-12
    • 2016-02-29
    相关资源
    最近更新 更多