Swift 和 Parse nil on prepareforsegue

Swift and Parse nil on prepareforsegue

我正在使用 Parse 中的数组编写 table 视图控制器。我需要通过 segue 发送数据,但我不知道为什么它总是返回 nil。我将不得不发送图像和文本,但现在 我只是从标签 title1 中获取文本并将其插入到名为 example 的变量类型字符串中。

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "toDetail" {

        var detailScene = segue.destinationViewController as! detailViewController

        let cell = sender as! UITableViewCell
        let indexPath = tableView?.indexPathForCell(cell)

        detailScene.example = self.timelineData[indexPath!.row].title1?.text
    }

}

对于我用过的数组:

var timelineData : NSMutableArray = NSMutableArray()

和函数loaddata,与函数viewDidAppear

一起使用
func loaddata () {
    timelineData.removeAllObjects()

    var findTimelineData:PFQuery = PFQuery(className: "ii")

    findTimelineData.findObjectsInBackgroundWithBlock{
        (objects, error)->Void in

        if error == nil{
            for object in objects!{
                let ii:PFObject = object as! PFObject
                self.timelineData.addObject(ii)
            }
            let array:NSArray = self.timelineData.reverseObjectEnumerator().allObjects
            self.timelineData = NSMutableArray(array: array)
            self.tableView.reloadData()
        }
    }
}

你最后一行代码肯定有问题:

detailScene.example = self.timelineData[indexPath!.row].title1?.text

我假设 self.timelineData 数组包含一些数据。
如果你的数组包含 String class 你不需要附加 .title1?.text 部分。
如果您的数组包含 UILabel class 您需要将行更改为

detailScene.example = self.timelineData[indexPath!.row].text

因为UILabel没有属性叫title1

总的来说,我认为这是因为 self.timelineData 数组中的 class 没有 属性 调用 title1

试试这个。它至少应该让您到达从正确的单元格中获取信息的地步。我假设您的 timelineData 数组充满了文本,所以这就是我通过将其转换为字符串来访问它的方式。如果它充满了不同类型的对象,则需要以不同的方式进行转换。

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if segue.identifier == "toDetail" {
        if let detailScene = segue.destinationViewController as? detailViewController {
            if let indexPath = tableView.indexPathForSelectedRow()?.row {
                var object = self.timelineData[indexPath] as! PFObject
                var title = object["title"] as! String
                detailScene.example = title
            }
        }
    }

}

可能是来自 indexPathForCell 的 return 值是 returning nil 或错误值。有不少文章说这个功能不可靠

一个常见的建议是改用 indexPathForRowAtPoint(cell.center)