gpt4 book ai didi

swift - 在解析中从用户获取对象

转载 作者:行者123 更新时间:2023-11-30 10:10:28 24 4
gpt4 key购买 nike

在 Collection View 中,我有一个事件数组,每个单元格都有一个事件图像的背景 ImageView ,该图像保存为 PFFile。在我添加这段代码之前,它工作得很好。用户有一个属性“profilePicture”,我也想在单元格中显示它。这是我的代码,位于获取事件图像的 block 内部。

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!)

})

这是获取事件及其所有属性的完整方法(就像我所说的,在添加上述代码之前工作得很好。现在它抛出一个“ fatal error :在展开可选值时意外发现 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
}
}
})

最佳答案

强制将零值可选变量转换为非可选变量将导致运行时错误。为什么使用 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!)

})
}
}

关于swift - 在解析中从用户获取对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33225076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com