2015-07-10 33 views
-1

我無法處理來自Parse的圖像。我創建了一個函數來從Parse類中獲取所有圖像文件,並將它們保存到字典中(鍵值爲objectId)。任何想法爲什麼和/或如何解決?以下是代碼:Swift - 獲得雙?使用UIImage時出錯

private func generateDictionaryOfImages(imageKeyToLookup: String, dictionaryKeyToReturn: String) { 

    for object in objectList { 
     var currentObjectId = object.objectId! 
     var image = UIImage() 

     let imageFile = object[imageKeyToLookup] as! PFFile 

     imageFile.getDataInBackgroundWithBlock({ (data: NSData?, error: NSError?) -> Void in 

     if data != nil { 
      if let imageData = data { 
      image = UIImage(data: imageData)! 
      } 

     } 
     }) 
// This imageDictionary is copied to the downloadedClientImages variable separately 
     self.imageDictionary[currentObjectId] = image 
    } 
    } 


func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

    let cell = tableView.dequeueReusableCellWithIdentifier("Profile") as! ProfileTableViewCell 

    let title: String = grandCentral.returnValueForKeyAtIndexPath(indexPath.row, key: "forename") as! String 
    let currentUserId: String = grandCentral.returnCurrentUserId() 

// Error is generated here. '@lvalue UIImage??' is not convertible to 'UIImage' 
    let image: UIImage = downloadedClientImages[currentUserId] 
    cell.setCell(title, image: image) 

    return cell 
    } 
+0

這裏不足爲奇。問題是什麼? – matt

+0

如何聲明'self.imageDictionary'和'downloadedClientImages'? – ndmeiri

+0

@ndmeiri self.imageDictionary = [String:UIImage]() 和var downloadedClientImages:[String:UIImage?] = [String:UIImage]() then downloadedClientImages = grandCentral.returnDictionaryOfImages() –

回答

0

您需要在從字典中訪問它之後解包可選。

if let image = downloadedClientImages[currentUserId] { 
    cell.setCell(title, image: image) 
} 
+0

謝謝。爲什麼圖像回到可選狀態?我沒有具體說明UIImage在任何時候都是可選的?有點困惑爲什麼發生這個問題......? –

+0

如果找不到密鑰,字典就不知道該返回什麼,所以它返回可選項並強制您檢查它。 –