2016-03-17 56 views
0

我想實現從加載數據並導航到guestVC點擊後VC上的按鈕加載數據從分析服務器。它工作正常,並在某個時候開始崩潰的應用程序...不知道爲什麼?我得到致命的錯誤:意外地發現零,同時解開可選值...任何和所有的方向或幫助將不勝感激。謝謝!意外地發現零,同時展開一個可選的值調度異步

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 

       }) 
      }) 

    } 

回答

0

您使用大量感嘆號強制在代碼中打開可選值,這是一個壞習慣。 例如,您可以安全地解包guestname.last:

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

好的,謝謝。那麼我在else語句中返回什麼?當我繼續訪問guestVC時,使用guestname.last返回查詢時,有幾個實例出現錯誤。 – user3708224

+0

該應用程序崩潰,因爲guestname.las爲零(guest虛擬機名稱爲空),但您嘗試將其解包。在其他情況下,您可以處理客人姓名爲空的情況(可能會在警報視圖中顯示錯誤) –

0

在添加或附加之前,檢查字典鍵是否有效。檢查字典中的'uuid'或'pic'鍵是否有價值。如果它已添加/追加。

相關問題