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)")
}
}
}