Chapter 1 - Saving to Core Data - Error message

After folloring the code examples from the 1st Chapter, I got an error message. I’m not sure what selector where was sent. I’d really appreciate if someone point me where exactly was a mistake.

-[TestList.ViewController AddName:]: unrecognized selector sent to instance 0x7f917ed075a0
2022-02-16 11:20:00.834944+0100 TestList[29566:3817790] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[TestList.ViewController AddName:]: unrecognized selector sent to instance 0x7f917ed075a0'
*** First throw call stack:
(
	0   CoreFoundation                      0x00007fff20422fba __exceptionPreprocess + 242
	1   libobjc.A.dylib                     0x00007fff20193ff5 objc_exception_throw + 48
	2   CoreFoundation                      0x00007fff20431d2f +[NSObject(NSObject) instanceMethodSignatureForSelector:] + 0
	3   UIKitCore                           0x00007fff246f60f1 -[UIResponder doesNotRecognizeSelector:] + 292
	4   CoreFoundation                      0x00007fff204274cf ___forwarding___ + 1455
	5   CoreFoundation                      0x00007fff204297a8 _CF_forwarding_prep_0 + 120
	6   UIKitCore                           0x00007fff246c7937 -[UIApplication sendAction:to:from:forEvent:] + 83
	7   UIKitCore                           0x00007fff23beccc5 -[UIBarButtonItem _triggerActionForEvent:] + 158
	8   UIKitCore                           0x00007fff23bc45d3 __45-[_UIButtonBarTargetAction _invoke:forEvent:]_block_invoke + 39
	9   UIKitCore                           0x00007fff23bc4484 -[_UIButtonBarTargetAction _invoke:forEvent:] + 152
	10  UIKitCore                           0x00007fff246c7937 -[UIApplication sendAction:to:from:forEvent:] + 83
	11  UIKitCore                           0x00007fff23fe845d -[UIControl sendAction:to:forEvent:] + 223
	12  UIKitCore                           0x00007fff23fe8780 -[UIControl _sendActionsForEvents:withEvent:] + 332
	13  UIKitCore                           0x00007fff23fe707f -[UIControl touchesEnded:withEvent:] + 500
	14  UIKitCore                           0x00007fff24703d01 -[UIWindow _sendTouchesForEvent:] + 1287
	15  UIKitCore                           0x00007fff24705b8c -[UIWindow sendEvent:] + 4792
	16  UIKitCore                           0x00007fff246dfc89 -[UIApplication sendEvent:] + 596
	17  UIKitCore                           0x00007fff247727ba __processEventQueue + 17124
	18  UIKitCore                           0x00007fff24768560 __eventFetcherSourceCallback + 104
	19  CoreFoundation                      0x00007fff20390ede __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
	20  CoreFoundation                      0x00007fff20390dd6 __CFRunLoopDoSource0 + 180
	21  CoreFoundation                      0x00007fff2039029e __CFRunLoopDoSources0 + 242
	22  CoreFoundation                      0x00007fff2038a9f7 __CFRunLoopRun + 875
	23  CoreFoundation                      0x00007fff2038a1a7 CFRunLoopRunSpecific + 567
	24  GraphicsServices                    0x00007fff2b874d85 GSEventRunModal + 139
	25  UIKitCore                           0x00007fff246c14df -[UIApplication _run] + 912
	26  UIKitCore                           0x00007fff246c639c UIApplicationMain + 101
	27  libswiftUIKit.dylib                 0x00007fff53fcbf42 $s5UIKit17UIApplicationMainys5Int32VAD_SpySpys4Int8VGGSgSSSgAJtF + 98
	28  TestList                            0x0000000106c6647a $sSo21UIApplicationDelegateP5UIKitE4mainyyFZ + 122
	29  TestList                            0x0000000106c663ee $s8TestList11AppDelegateC5$mainyyFZ + 46
	30  TestList                            0x0000000106c66599 main + 41
	31  libdyld.dylib                       0x00007fff2025abbd start + 1
	32  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi: terminating with uncaught exception of type NSException
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[TestList.ViewController AddName:]: unrecognized selector sent to instance 0x7f917ed075a0'
terminating with uncaught exception of type NSException
CoreSimulator 757.5 - Device: iPhone 8 (C38168C8-DD83-4E4B-93E2-5CD65EE4246E) - Runtime: iOS 14.5 (18E182) - DeviceType: iPhone 8

Thanks!

Could you share a snip of code that is making the call (TestList)? It’s possible there may be a typo somewhere.

Yes, sure!

import UIKit
import CoreData

// MARK: - UITableViewDataSource
extension ViewController: UITableViewDataSource {
    
  func tableView(_ tableView: UITableView,
                 numberOfRowsInSection section: Int) -> Int {
    return people.count
  }
    
  func tableView(_ tableView: UITableView,
                 cellForRowAt indexPath: IndexPath)
                 -> UITableViewCell {
    
    let person = people[indexPath.row]
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    
    cell.textLabel?.text = person.value(forKeyPath: "name") as? String
    return cell
  }
}

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    
    var people: [NSManagedObject] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        title = "The List"
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        
    }
    

    @IBAction func addName(_ sender: UIBarButtonItem) {
        let alert = UIAlertController(title: "New Name",
                                        message: "Add a new name",
                                        preferredStyle: .alert)
        
        let saveAction = UIAlertAction(title: "Save", style: .default) {
          [unowned self] action in
          guard let textField = alert.textFields?.first,
                let nameToSave = textField.text else {
            return
        }
          self.save(name: nameToSave)
          self.tableView.reloadData()
        }
        
        let cancelAction = UIAlertAction(title: "Cancel",
                                           style: .cancel)
        alert.addTextField()
        alert.addAction(saveAction)
        alert.addAction(cancelAction)
        present(alert, animated: true)
    }
    
    func save(name: String) {
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
            return
        }
        // 1
        let managedCOntext = appDelegate.persistentContainer.viewContext
        
        // 2
        let entity = NSEntityDescription.entity(forEntityName: "Person", in: managedCOntext)!
        let person = NSManagedObject(entity: entity, insertInto: managedCOntext)
        
        // 3
        person.setValue(name, forKeyPath: "name")
        
        // 4
        do {
            try managedCOntext.save()
            people.append(person)
        } catch let error as NSError {
            print("Could not save.\(error),\(error.userInfo)")
        }
    }
    

}

Do you need the Main.storyboard as well? But I’m not sure how to share it:/

No need for the Storyboard, I’m going to check this out. I need to fetch the book.

OK, I looked at your source and see that the extension is declared above the class declaration. You may want to move that down.

I wasn’t able to reproduce the issue, we can try a few things:

  1. Try downloading the final version of the project and building it: https://github.com/raywenderlich/cdt-materials/tree/editions/8.0 (01-your-first-core-data-app/projects/final) - if it all works as expected, start over with your project, a step may have been missed.
  2. Upload your code to a Github repo, I can fetch the whole project and will be able to solve the issue easier.