2015-09-28 57 views
1

我正在製作一個簡單的應用程序,並實現userInformation部分。用戶可以編輯他的信息,但是我遇到了麻煩,如果用戶沒有提供任何信息,當我嘗試從未定義的列中檢索數據時,它會崩潰。如何檢查我的Parse中的值是否未定義?

這是我的代碼來檢索用戶數據。如果有數據要解析,它不會崩潰,否則會。

let nickName = PFUser.currentUser()?.objectForKey("nickName") as! String 

所以我問我如何處理崩潰前檢索未定義的值? (請給我寫完整的代碼)

有沒有一種方法可以在檢索之前檢查值?

///like this 
if (value in parse == "ABC") { 
    print("yes") 
} 
+0

這可能幫助http://stackoverflow.com/questions/25779392/swift-optional-text-in-optional-value – sakhunzai

+0

你告訴它崩潰,如果它不能解壓縮到一個字符串 - 只是停止這樣做... – Wain

+0

我不太瞭解曲estion。你爲什麼不檢查'objectForKey'是否返回零或不展開底層值之前? –

回答

0

這裏,試試這個代碼:

let query = PFUser.query() 
    query!.whereKey("username", equalTo: "abcd") 
    query!.findObjectsInBackgroundWithBlock({ 
     (object, error) -> Void in 
     if (object != nil) { 
      if(object!.count != 0) 
      { 
       for messageObject in object! { 
        let photoUploaded : Bool = ((messageObject as! PFObject)["photoUploaded"] as? Bool)! 
        if (photoUploaded == true) { 
         if let userPicture = messageObject["profilePic"] as? PFFile { 
          userPicture.getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) -> Void in 
           if (error == nil) { 
            let imageData = imageData 
            let image = UIImage(data: imageData!) 
            self.createrImage.image = image 
           } else { 
            // Error handling 
           } 
          } 
         } 

        } 
       } 
      } // object is undefined here 
     } // else is added here to get object is nill 
    }) 

如果照片是與用戶數據上傳我檢查。如果上傳,我會得到true作爲Bool值,如果沒有上傳,那麼false。如果未定義,則在註釋處添加else部分和斷點以避免崩潰。更新我的任何問題的情況下

如果你想檢索通過查詢對象(僅定義的對象),那麼u需要看到

query.whereKeyExists("nickName"); 

如果u只是想查詢檢索coulmn的值被定義或者不是你

2

可以簡單地使用

if(user["nickName"]) 
{ 
    // nickname exists for user ; 
} 
相關問題