Is NSDocument and CoreData a possible combination, or is NSPersistentDocument the only way?

Deadly 提交于 2019-12-07 04:01:03

问题


I'm making an application which creates course timetables for people at my school. This is the rough design I had in mind for the application:

I'd like my NSDocument subclass to represent an individual's timetable. The idea is that they open up a document, and can add courses from a pool to their timetable, then save, share, open, etc. So the timetable will be stored in an external file, chosen by the user.

I'd like to use CoreData to store all the courses from which students can choose. These will not be altered with the creation and editing of timetables, but instead, likely only on launch of the application, when it checks for updates to the course info.

This seems to be the logical way to structure my app. The problem is, when I create an NSDocument-based application and check the use CoreData box, instead of making it an NSDocument-based app with CoreData facilities, it makes it an NSPersistentDocument-based app.

I don't think this is the behaviour I want. Is there a way to use CoreData, but still have an NSDocument-based application? Or is NSPersistentDocument what I should be using after all? Am I misunderstanding the whole NS*Document business? Do you have any advice for my application's structure?

Thanks for any help!


回答1:


Yes, you can use Core Data without using NSPersistentDocument. Just instantiate NSPersistentStoreCoordinator and NSManagedObjectContext directly. Here's some code: how do you create a NSManagedObjectContext

If you want to share an instance of the catalog among multiple NSDocument instances, and don't want to persist the catalog along with each document, this is a good way to go. Your application or app delegate can take care of loading the course catalog, and your document can take take care of loading and saving an individual student's timetable. You'll have to implement that yourself, using a keyed archiver, say, or by writing a plist yourself.

Instead, if you like, you can further leverage Core Data. Represent student schedules with NSManagedObjects and let NSPersistentDocument handle loading and saving the contexts. You get a lot of useful functionality, such as undo–redo, for free.



来源:https://stackoverflow.com/questions/7721392/is-nsdocument-and-coredata-a-possible-combination-or-is-nspersistentdocument-th

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