在展开Optional值dispatch-async时意外发现nil

时间:2016-03-17 03:41:02

标签: ios swift fatal-error dispatch-async optional-values

我试图在点击postVC上的按钮加载数据并导航到guestVC后,从Parse服务器实现加载数据。它工作正常,在某些时候开始崩溃应用程序...不知道为什么?我得到了致命的错误:在打开一个可选值时意外地发现了nil ...任何和所有方向或帮助将不胜感激。谢谢!

import UIKit
import Parse

var postuuid = [String]()

class postVC: UITableViewController {

//postVC button click function
//clicked username button from post
    @IBAction func usernameBtn_click(sender: AnyObject) {
        let i = sender.layer.valueForKey("index") as! NSIndexPath
        let cell = tableView.cellForRowAtIndexPath(i) as! postCell

        // if user tapped on himself go home, else go guest
        if cell.usernameBtn.titleLabel?.text == PFUser.currentUser()?.username {
            let home = self.storyboard?.instantiateViewControllerWithIdentifier("homeVC") as! homeVC
            self.navigationController?.pushViewController(home, animated: true)    
        } else {
            let guest = self.storyboard?.instantiateViewControllerWithIdentifier("guestVC") as! guestVC
            self.navigationController?.pushViewController(guest, animated: true)
        }  
    } 



// guestVC relevant code
import UIKit
import Parse

var guestname = [String]()

class guestVC: UICollectionViewController {

    var uuidArray = [String]()
    var picArray = [PFFile]()

    // posts loading function
    func loadPosts() {     

            let query = PFQuery(className: "posts")
// app keeps crashing in line below when I try to load data to guestVC
            query.whereKey("username", equalTo: guestname.last!)
            query.limit = self.page
            query.findObjectsInBackgroundWithBlock( { (objects:[PFObject]?, error:NSError?) -> Void in

                if error == nil {

                    self.uuidArray.removeAll(keepCapacity: false)
                    self.picArray.removeAll(keepCapacity: false)

                    for object in objects! {
                        self.uuidArray.append(object.valueForKey("uuid") as! String)
                        self.picArray.append(object.valueForKey("pic") as! PFFile)
                    }

                    self.collectionView?.reloadData()
                } else {
                    print(error!.localizedDescription)
                }
                dispatch_async(dispatch_get_main_queue(), { () -> Void in

                    // code here will be executed as the main queue

                })
            })

    }

2 个答案:

答案 0 :(得分:0)

在添加或附加之前,检查字典键是否具有有效值。检查是否' uuid'或者' pic' key在字典中是否有价值。如果有,则添加/追加。

答案 1 :(得分:0)

你使用很多惊叹号来强制解包代码中的可选值,这是一个坏习惯。 例如,您可以通过以下方式安全地解包guestname.last:

guard let lastItem = guestname.last else {
// do something else
return
}
query.whereKey("username", equalTo: lastItem)