Code showing No Results when run

Hello:



I have the following code. I am developing an app for Mac OS. I have a UI with text fields for user input which is saved after each item is entered. When I run the code I get no errors but also I get no response from the print statements. I did not cast any fields as delegates. If that is necessary, How can I did that?


I would appreciate any help with the code that may identify the problem.


import AppKit

import Cocoa

import Foundation

import CoreData


class RegistrationViewController: NSViewController, NSApplicationDelegate {



var students: [NSManagedObject] = []


@IBOutlet weak var firstNameTextField: NSTextField!



override func viewDidLoad() {

super.viewDidLoad()


firstNameTextField.stringValue = UserDefaults().string(forKey: "fnTextFieldKey") ?? ""

}

override func viewDidAppear() {

print("Documents Directory: ", FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last ?? "Not Found!")

}


@IBAction func saveFirstName(_ sender: Any) {


print ("starting code for save name field")

guard (NSApplication.shared.delegate as? AppDelegate) != nil else {

return

}

print ("Initializing Managed Object Context"

)

let managedContext = persistentContainer.viewContext

let entity = NSEntityDescription.entity(forEntityName: "Registration", in: managedContext)!

let component = NSManagedObject(entity: entity, insertInto: managedContext)

UserDefaults().string(forKey: "fnTextFieldKey")

component.setValue (NSTextField.self, forKeyPath: "firstName")

print (NSTextField.self)

do {

try managedContext.save()

students.append(component)

print ("SAVED")

} catch let error as NSError {

print("Could not save. \(error), \(error.userInfo)")

}

}


}

What is the saveFirstName IBAction connected to? If you don't connect the action to a user interface element, it will never get called.


By the way, the Cocoa framework includes both the AppKit and Foundation frameworks. You can remove the lines of code that import AppKit and Foundation.

It is connected to a button "SAVE".

The only other thing I can tell you is to check that the class of the view controller in your storyboard is RegistrationViewController and not NSViewController. Open your storyboad and open the identity insprctor by choosing View > Inspectors > Show Identity Inspector. In the Custom Class section, set the class to RegistrationViewController.


If that doesn't work, you're going to have to provide more information on how you have set up your storyboards, user interface, view controllers, and connections. You provided a code sample, but there's nothing in the code that explains why the saveFirstName IBAction never gets called. No one is going to be able to help you unless you provide the additional information on how you set up your storyboards.

The class is indeed "RegistrationViewController".

Code showing No Results when run
 
 
Q