问题
I have spent more than a day on trying to find a simple example of how to use an NSObjectController
for binding along with core data. All examples are of NSArrayControllers
with NSTableView
bindings.
How would you setup a simple NSObjectController
with core data to automatically save and fetch data? Lets say you want to bind an entity with a string attribute to a text field, how would you do this?
回答1:
Here are the basics in Interface builder.
Drag over an
nstextfield
into a view (from the object library)Drag over a
nsobjectcontroller
(likewise)Open the bindings inspector. Option-Cmd-7 or View/Utilities/BindingsInspector.
Select the above
nsobjectcontroller
. Within BindingsInspector, near the bottom is the parameter for ManagedObjectContext. Click the checkbox next to "Bind to'. Then select the File'sOwner (from the dropdown). The File's Owner is likely your NSDocument. Set the ModelKeyPath to managedObjectContext (note the lowercase 'm')Now switch the Utility view to AttributesInspector (Open-Cmd-4). Set the Mode from "Class" to "Entity". Type in the name of your BusinessObject or Model name. Such as "Employee".
Select your new
nstextfield
. In the BindingsInspector, choose "Value". Checkmark "Bind to" and select the abovensobjectcontroller
(from the dropdown).For the CONTROLLER KEY choose "selection".
For the MODEL KEY PATH choose a models attribute (but not a relationship) like "name".
Now experiment by adding a second controller, an nsarraycontroller. The are bound to relationships, not attributes. Thus the arrays have plural "Content Set" , not singular "Content". Its worth nothing that relationships have the underlying NSSet, while ALL attributes are subclasses of NSObject. No int, float. But NSNumber, NSString.
Select the new nsarraycontroller. Choose "Bind to" in Content Set. Select the first nsobjectcontroller. The CONTROLLER KEY is "selection" while the MODEL KEY PATH is the relationship name, like "employees"
Set up a NSTableView, with several columns. (A table has many rows that accommodate the items in the set, and have columns to accommodate the various attributes in the entity)
Select one table column. Select "Bind to" and choose the nsarraycontroller.
This time the CONTROLLER KEY is "arrangedObjects" (not selection). The MODEL KEY PATH is simply an attribute name like "name'.
Note that NSNumber and NSDate prefer NSFormatters so drag those (from object library) into a nstextfield or table column to convert from a number and date to a nice string.
来源:https://stackoverflow.com/questions/16883967/how-to-use-nsobjectcontroller-with-core-data