2
votes

I'm new to SWIFT programming and am trying to do a simple app to learn to use core data and bind it to display in an app. I've looked at loads of examples but all seem to be old. I am working in XCode 9.

I started with a MacOS Cocoa app with Core Data. I have a simple entity called "Workout" with 4 attributes date, seconds, sport and rpe.

I then added a Array Controller under the view controller scene. I added a Table view which set the Array Controller as the data source. I've added buttons to add and delete linking to array controllers add and remove methods.

I think all I need to do now is to bind the Array Controller to the managedObjectContext of my Core Data Model. This is found in the AppDelegate. However when I select the Array Controller and go to Bindings and select Parameters the only options to bind to are "View Controller" and "Shared User Defaults Controller". I've selected View Controller but cannot figure out the Model Key Path to link in to my data model.

I feel I must be missing something obvious. I feel there must either be a way to bind to the AppDelegate or a Model Key Path from the View Controller but I can't figure out either. Any help much appreciated.

2

2 Answers

3
votes

In a storyboard based project there is no (binding) reference from a view controller to the AppDelegate class.

A solution is to add a property and override init?(coder in the view controller

@objc let managedObjectContext: NSManagedObjectContext

required init?(coder: NSCoder) {
    self.managedObjectContext = (NSApp.delegate as! AppDelegate).persistentContainer.viewContext
    super.init(coder: coder)
}

then bind the ManagedObjectContext to ViewController -> managedObjectContext.

In the Attribute Inspector of the array controller don't forget to set the Mode to Entity Name, insert the entity name and check Prepares Content.

0
votes

To fix [<Core_Data_Binding.ViewController 0x6080000c4600> valueForUndefinedKey:]: this class is not key value coding-compliant for the key managedObjectContext change let managedObjectContext: NSManagedObjectContext in vadian's code to @objc let managedObjectContext: NSManagedObjectContext. XCode 9 by default does not expose properties and methods to Objective C: The use of Swift 3 @objc inference in Swift 4 mode is deprecated?