Swift - 核心数据运行时错误

时间:2014-12-24 00:11:26

标签: ios core-data swift

我尝试在单元格中创建textLabels数组时遇到此运行时错误。

我的代码如下所示:

    else {
        mySelectedCell.accessoryType = UITableViewCellAccessoryType.Checkmark
        mySelectedCell.tintColor = UIColor.blackColor()

        if let tx = mySelectedCell.textLabel?.text as Optional?{

            var textLabel:String = String()                
            textLabel = tx!                
            var tempFriend = Model(entity: en!, insertIntoManagedObjectContext: context)

            //Save user to core data                
            tempFriend.tempUser = textLabel

            //Save context 
            context.save(nil)

            //Make list from objects   
            liste = context.executeFetchRequest(freq, error: nil)!

            //Make new list of strings from first list

            for var i = 0; i < liste.count; ++i{

                var data:NSManagedObject = liste[i] as NSManagedObject
                //The next line is where the error appears
                 showList.append(data.valueForKeyPath("tempUser") as String)
            }

            //Show list                
            println(showList)

          }
        }
      }

我的错误说:

  

致命错误:在展开Optional值时意外发现nil   (LLDB)。

我不明白为什么某些东西会在我的代码中返回"nil"

任何想法都会受到赞赏。

1 个答案:

答案 0 :(得分:0)

你强行展开一个零的可选值。由于您已经省略了错误的堆栈跟踪,因此很难分辨哪一个。试试这个:

else {
    mySelectedCell.accessoryType = UITableViewCellAccessoryType.Checkmark
    mySelectedCell.tintColor = UIColor.blackColor()

    if let textLabel = mySelectedCell.textLabel?.text,
       let entity = en {

        var tempFriend = Model(entity: entity, insertIntoManagedObjectContext: context)

        //Save user to core data                
        tempFriend.tempUser = textLabel

        //Save context 
        context.save(nil)

        //Make list from objects   
        liste = context.executeFetchRequest(freq, error: nil)!

        //Make new list of strings from first list

        for var i = 0; i < liste.count; ++i{

            var data:NSManagedObject = liste[i] as NSManagedObject
            //The next line is where the error appears
             showList.append(data.valueForKeyPath("tempUser") as String)
        }

        //Show list                
        println(showList)

      }
    }
  }