未捕获的异常错误Swift 2.0

时间:2015-11-05 10:59:58

标签: swift

当我点击表格单元格以转移到内部表格时,我收到此错误。在将代码复制到另一个View Controller以提高效率之后,问题就开始发生了,但是在撤消所有这些操作后我仍然会收到错误

2015-11-05 21:52:07.505 Grades[11134:1292199] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<Grades.AssesmentViewController 0x7fb660743fe0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key addAssesment.'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000010623af45 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x0000000107f5edeb objc_exception_throw + 48
    2   CoreFoundation                      0x000000010623ab89 -[NSException raise] + 9
    3   Foundation                          0x0000000106603a6b -[NSObject(NSKeyValueCoding) setValue:forKey:] + 288
    4   UIKit                               0x0000000106be204c -[UIViewController setValue:forKey:] + 88
    5   UIKit                               0x0000000106e0fa71 -[UIRuntimeOutletConnection connect] + 109
    6   CoreFoundation                      0x000000010617ba80 -[NSArray makeObjectsPerformSelector:] + 224
    7   UIKit                               0x0000000106e0e454 -[UINib instantiateWithOwner:options:] + 1864
    8   UIKit                               0x0000000107171730 -[UIStoryboard instantiateViewControllerWithIdentifier:] + 181
    9   UIKit                               0x000000010717634c -[UIStoryboardSegueTemplate instantiateOrFindDestinationViewControllerWithSender:] + 90
    10  UIKit                               0x00000001071765a9 -[UIStoryboardSegueTemplate _perform:] + 52
    11  UIKit                               0x000000010717688b -[UIStoryboardSegueTemplate perform:] + 156
    12  UIKit                               0x0000000106b979b1 -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:] + 1856
    13  UIKit                               0x0000000106b97c76 -[UITableView _userSelectRowAtPendingSelectionIndexPath:] + 388
    14  UIKit                               0x0000000106a631ba _runAfterCACommitDeferredBlocks + 317
    15  UIKit                               0x0000000106a76396 _cleanUpAfterCAFlushAndRunDeferredBlocks + 95
    16  UIKit                               0x0000000106a821c2 _afterCACommitHandler + 90
    17  CoreFoundation                      0x0000000106166947 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
    18  CoreFoundation                      0x00000001061668b7 __CFRunLoopDoObservers + 391
    19  CoreFoundation                      0x000000010615c50b __CFRunLoopRun + 1147
    20  CoreFoundation                      0x000000010615be08 CFRunLoopRunSpecific + 488
    21  GraphicsServices                    0x000000010a857ad2 GSEventRunModal + 161
    22  UIKit                               0x0000000106a5730d UIApplicationMain + 171
    23  Grades                              0x0000000105cc4e1d main + 109
    24  libdyld.dylib                       0x0000000108a6f92d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

这是我第一个ViewController的代码:

import UIKit
import CoreData

class ViewController: UIViewController, UITableViewDataSource {


    @IBOutlet weak var tableView: UITableView!
    var subjects = [NSManagedObject]()
    override func viewDidLoad() {
        super.viewDidLoad()

    }

    func tableView(tableView: UITableView,
        numberOfRowsInSection section: Int) -> Int {
            return subjects.count
    }

    func tableView(tableView: UITableView,
        cellForRowAtIndexPath
        indexPath: NSIndexPath) -> UITableViewCell {

            let cell =
            tableView.dequeueReusableCellWithIdentifier("Cell")

            let check = subjects[indexPath.row]

            cell!.textLabel!.text =
                check.valueForKey("name") as? String

            return cell!
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }

    @IBAction func addName(sender: AnyObject) {

        let alert = UIAlertController(title: "New Subject", message: "Add a new Subject", preferredStyle: .Alert)
        let saveAction = UIAlertAction(title: "Save",
            style: .Default,
            handler: { (action:UIAlertAction) -> Void in

                let textField = alert.textFields!.first
                if textField != nil {
                    self.saveSubject(textField!.text!)
                    self.tableView.reloadData()
                }
                else {

                }
        })


        let cancelAction = UIAlertAction(title: "Cancel",
            style: .Default) { (action: UIAlertAction) -> Void in
        }

        alert.addTextFieldWithConfigurationHandler {
            (textField: UITextField) -> Void in
        }
        alert.addAction(saveAction)
        alert.addAction(cancelAction)

        presentViewController(alert,
            animated: true,
            completion: nil)
    }
    func saveSubject(subject: String) {

        let appDelegate =
        UIApplication.sharedApplication().delegate as! AppDelegate

        let managedContext = appDelegate.managedObjectContext


        let entity =  NSEntityDescription.entityForName("Subjects",
            inManagedObjectContext:managedContext)

        let check = NSManagedObject(entity: entity!,
            insertIntoManagedObjectContext: managedContext)


        check.setValue(subject, forKey: "name")


        do {
            try managedContext.save()

            subjects.append(check)
        } catch let error as NSError  {
            print("Could not save \(error), \(error.userInfo)")
        }
    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)


        let appDelegate =
        UIApplication.sharedApplication().delegate as! AppDelegate

        let managedContext = appDelegate.managedObjectContext


        let fetchRequest = NSFetchRequest(entityName: "Subjects")


        do {
            let results =
            try managedContext.executeFetchRequest(fetchRequest)
            subjects = results as! [NSManagedObject]
        } catch let error as NSError {
            print("Could not fetch \(error), \(error.userInfo)")
        }
        func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle,forRowAtIndexPath indexPath: NSIndexPath) {

        }
    }

    func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
        self.performSegueWithIdentifier("ShowAssesment", sender: self);


    }

}

我的第二视图控制器:

import UIKit
import CoreData

class AssesmentViewController: UITableViewController {

    @IBOutlet weak var navTitle: UINavigationItem!
    var assesments = [NSManagedObject]()
    let cellIdentifier = "Cell"
    var subjectSelected = String()


    override func viewDidLoad() {
        print(subjectSelected)

    }

    func assesmentForDisplay(atIndexPath indexPath: NSIndexPath){


    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath)
        //cell.textLabel?.text = assesments[indexPath.row]
        return cell

    }

    func changeNavTitle(newTitle: String) {
        title = newTitle
    }

    @IBAction func addAssesment(sender: AnyObject) {
        let alert = UIAlertController(title: "New Assesment", message: "Add a new Assesment", preferredStyle: .Alert)
        let saveAction = UIAlertAction(title: "Save",
            style: .Default,
            handler: { (action:UIAlertAction) -> Void in

                let textFieldName = alert.textFields!.first

                    self.saveAssesment(textFieldName!.text!)
                    self.tableView.reloadData()


        })


        let cancelAction = UIAlertAction(title: "Cancel",
            style: .Default) { (action: UIAlertAction) -> Void in
        }



        alert.addTextFieldWithConfigurationHandler {
            (textField: UITextField) -> Void in
            textField.placeholder = "Name"
        }
        alert.addAction(saveAction)
        alert.addAction(cancelAction)

        presentViewController(alert,
            animated: true,
            completion: nil)

    }

    func saveAssesment(subject: String) {

        let appDelegate =
        UIApplication.sharedApplication().delegate as! AppDelegate

        let managedContext = appDelegate.managedObjectContext


        let entity =  NSEntityDescription.entityForName("Assesment",
            inManagedObjectContext:managedContext)

        let check = NSManagedObject(entity: entity!,
            insertIntoManagedObjectContext: managedContext)


        check.setValue(subject, forKey: "name")


        do {
            try managedContext.save()

        } catch let error as NSError  {
            print("Could not save \(error), \(error.userInfo)")
        }
    }



}

我的所有Outlets和IBActions都与故事板中的按钮和tableview相关联。

1 个答案:

答案 0 :(得分:0)

如果您正在使用故事板,则只需单击AssesmentViewController并选择它们的连接检查器。检查是否有任何感叹号(连接丢失)。

正确删除它们。然后再次运行项目。

enter image description here