错误:在解包可选值时意外发现nil

编程入门 行业动态 更新时间:2024-10-25 22:29:34
本文介绍了错误:在解包可选值时意外发现nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我一直在制作应用程序是Swift但我在TableViewController类中一直出错。我找不到任何方法来解决这个问题,并继续收到此错误:

I have been making an app is Swift but I keep getting an error in my TableViewController class. I could not find any way to fix this and kept getting this error :

override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let cell : TextTableViewCell = tableView!.dequeueReusableCellWithIdentifier("Cell", forIndexPath : indexPath!) as TextTableViewCell let madan : PFObject = self.timeLineData.objectAtIndex(indexPath!.row) as PFObject cell.timestampLabel.alpha = 0 cell.usernameLabel.alpha = 0 cell.madanTextView.alpha = 0 cell.madanTextView.text = madan.objectForKey("content") as String var dateFormatter : NSDateFormatter = NSDateFormatter() dateFormatter.dateFormat = "MM-dd-yyyy HH:mm" cell.timestampLabel.text = dateFormatter.stringFromDate(madan.createdAt) var findSender : PFQuery = PFUser.query() findSender.whereKey("objectId", equalTo: madan.objectForKey("sender").objectId) var i = 1 findSender.findObjectsInBackgroundWithBlock { (objects: [AnyObject]!, error: NSError!) -> Void in if !error { let user : PFUser = (objects as NSArray).lastObject as PFUser // Error here cell.usernameLabel.text = user.username UIView.animateWithDuration(0.5, animations: { cell.timestampLabel.alpha = 1 cell.usernameLabel.alpha = 1 cell.madanTextView.alpha = 1 }) } } return cell }

我找不到任何解决方法。

I cannot find any way to fix this.

推荐答案

看起来像如果对象以 nil 的形式返回。首先检查nil:

It looks as if objects is coming back as nil. First check for nil:

if !error { if let actualObjects = objects { let possibleUser = (actualObjects as NSArray).lastObject as? PFUser if let user = possibleUser { cell.usernameLabel.text = user.username // ... } } }

注意:我将更改为到为?。 lastObject 已经返回一个Optional,所以如果最后一个对象无法转换为PFUser,你也可以继续执行。另外,因为 lastObject 可能返回nil,你还需要检查 nil 。

Note: I changed your as to as?. lastObject is already returning an Optional and so you might as well let the execution continue if the last object cannot be converted to PFUser. Also, because lastObject might return nil, you also need to check that for nil.

更多推荐

错误:在解包可选值时意外发现nil

本文发布于:2023-11-26 14:10:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634095.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可选   意外   错误   发现   nil

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!