现在更改了Cell - 致命错误:在展开Optional值时意外地发现了nil

时间:2016-01-29 10:32:11

标签: ios swift uitableview tableview cloudkit

所以我正在使用swift在UITablview中处理单元格。我一直试图将我的单元格从标题更改为标题和副标题:

我之前的代码是:

var objects = CKRecord

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let reuseIdentifier = "Cell"
    var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier) as UITableViewCell?
    if (cell != nil) {
        cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: reuseIdentifier)
    }

    let object = objects[indexPath.row]
    cell!.textLabel!.text = object.objectForKey("Notes") as? String
    cell!.detailTextLabel?.text = object.creationDate.objectForKey("Notes") as? String
    return cell!
}

我改为:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let reuseIdentifier = "Cell"
        var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier) as UITableViewCell?
        if (cell != nil) {
            cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: reuseIdentifier)
        }

        let object = objects[indexPath.row]
        cell!.textLabel!.text = object.objectForKey("Notes") as? String
        var time = object.creationDate

        let formatter = NSDateFormatter()
        formatter.dateStyle = NSDateFormatterStyle.LongStyle
        formatter.timeStyle = .MediumStyle

        let formattedtime = formatter.stringFromDate(time)

        cell!.detailTextLabel?.text = formattedtime

        return cell!

首次运行时,代码工作正常,标题(单元格内容)和副标题(日期)显示完美!

但..

当我尝试在应用程序中添加新Note(添加新单元格)时,我收到以下错误:

  

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

我猜这与必须使用“!”有关。在我的新代码中,但我无法弄清楚如何解决这个问题。

这是添加的功能:

let record = CKRecord(recordType: "CloudNote")
record.setObject("NewNote", forKey: "Notes")
MyClipManager.SaveMethod(Database!, myRecord:record)
/// Need to create IF statement to make sure record save happened, Then complete below code
self.objects.append(record)
self.objects = self.objects.sort({ $0.creationDate?.compare(($1.creationDate)!) == NSComparisonResult.OrderedDescending })

    self.Refresh()
}

以前的问题供参考:

Select creationDate from CloudKit record

0 个答案:

没有答案