在集合视图中,我有一个事件数组,每个单元格都有一个事件图像的背景图像视图,该视图保存为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!)
})
以下是获取事件及其所有属性的完整方法(就像我说的那样,在我添加上面的代码之前工作得非常好。现在它抛出了一个"致命错误:意外地发现了nil同时解开一个可选值"错误。有什么帮助吗?
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
}
}
})
答案 0 :(得分:1)
强制将nil值可选变量强制转换为非可选变量将导致运行时错误。你为什么使用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!)
})
}
}