How to use NSObjectController with Core Data?

一个人想着一个人 提交于 2019-12-06 10:00:12

问题


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.

  1. Drag over an nstextfield into a view (from the object library)

  2. Drag over a nsobjectcontroller (likewise)

  3. Open the bindings inspector. Option-Cmd-7 or View/Utilities/BindingsInspector.

  4. 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')

  5. 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".

  6. Select your new nstextfield. In the BindingsInspector, choose "Value". Checkmark "Bind to" and select the above nsobjectcontroller (from the dropdown).

  7. For the CONTROLLER KEY choose "selection".

  8. 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.

  1. 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"

  2. 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)

  3. Select one table column. Select "Bind to" and choose the nsarraycontroller.

  4. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!