2015-10-19 46 views
0

在集合視圖中,我有一個事件數組,每個單元格都有一個保存爲PFFile的事件圖像的背景圖像視圖。這工作正常,直到我添加此代碼。用戶有一個屬性「profilePicture」,我也想在單元格中顯示。這是我的代碼,它是在獲取事件圖像的塊內部。從用戶分析對象

let eventCreator : PFUser = event?.objectForKey("user") as! PFUser 
let creatorImage : PFFile = eventCreator.objectForKey("profilePicture") as! PFFile 
creatorImage.getDataInBackgroundWithBlock({ (data, error) -> Void in 

    cell.creatorImageView.image = UIImage(data: data!) 

}) 

這裏是一個得到該事件的完整的方法和它的所有屬性(比如我說,工作完全正常之前,我加入了上面的代碼現在,它拋出一個「致命錯誤:意外發現零而展開的可選值」的錯誤。任何幫助嗎?

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 

    //sets up cell 

    let cell : EventCell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! EventCell 

    //adds attend action 

    cell.attendButton.addTarget(self, action: "buttonTapped:", forControlEvents: UIControlEvents.TouchUpInside) 

    //queries parse for events 

    let event = events?[indexPath.row] 

    event?.eventImage.getDataInBackgroundWithBlock({ (data, error) -> Void in 

     if let data = data, image = UIImage(data: data) { 

      if cell.isFlipped == false { 

      cell.eventBackgroundImage.image = image 
      cell.eventTitleLabel.text = event?.eventTitle 

      //gets profile picture of events creator 

      let eventCreator : PFUser = event?.objectForKey("user") as! PFUser 
      let creatorImage : PFFile = eventCreator.objectForKey("profilePicture") as! PFFile 
      creatorImage.getDataInBackgroundWithBlock({ (data, error) -> Void in 

       cell.creatorImageView.image = UIImage(data: data!) 

      }) 

      //sets correct category for cell image 

       if event?.category == "" { 
        cell.categoryImageView.image = nil 
       } 

       if event?.category == "The Arts" { 
        cell.categoryImageView.image = UIImage(named: "University") 
       } 

       if event?.category == "The Outdoors" { 
        cell.categoryImageView.image = UIImage(named: "Landscape") 
       } 

       //TODO finish categories 

      } 

      else if cell.isFlipped == true { 

       cell.eventDescriptionLabel.text = event?.eventDescription 
      } 
     } 
    }) 

回答

1

你爲什麼要使用as!運營商強行鑄造零值可選變量的非可選一個會導致運行時錯誤?你或許應該使用as?操作相反,並檢查任何nil值,以確保演員成功做任何事情。

[編輯] 嘗試這樣:

if let eventCreator = event?.objectForKey("user") as? PFUser { 
    if let creatorImage = eventCreator.objectForKey("profilePicture") as? PFFile { 
     creatorImage.getDataInBackgroundWithBlock({ (data, error) -> Void in 

      cell.creatorImageView.image = UIImage(data: data!) 

     }) 
    } 
} 
+0

是的,這將更有意義,但它拋出,當我把作爲一個錯誤?並告訴我將它改回來。 – Echizzle

+1

當然會抱怨。你需要用'if let'改寫兩行。 –

+0

我想,但不知道順序或語法。很顯然,將「如果」放在let前面並不起作用,你能向我展示一個你正在考慮的代碼的例子嗎? – Echizzle