开发者

Core Data, managed object context, NSArrayController.. straighten me out a bit

So I've got an .xcdatamodel with about a dozen Entities defined and related to each other, with attributes and so on. So far I've been trying this in to a GUI using NSTableViews to display/enter data, and NSArrayControllers that I instantiate for each entity. This is all working great. They all tie in to the App Delegate's Managed Object Context (MOC)

But now I'm trying to programmatically access the data in these arrays, and I'm finding it obtuse to do so. After a lot of reading it looks like what I should 开发者_StackOverflowREALLY do is go to the MOC to fetch data for a given Entity. I haven't worked through this yet, but ok.

What I don't understand though, is how to use Core Data when I'm NOT entering via NSTableView etc, and NOT using NSArrayControllers. Like if I wanted to totally handle some of my .xcdatamodel Entities in my project's Model packages (that don't touch a GUI). Do I need to still instantiate an NSArrayController so that I can "prepare content" of an Entity and have it be managed and initialized and all that? Or is there another way I can tie in with the MOC directly and add/remove/get the data for a given Entity?

What I'm saying is that I'm really unclear as to how to work with things unless I'm doing simple case View <-> NSArrayController and then Model <-> MOC


You should take a look at NSFetchRequest and the executeFetchRequest:error: method on NSManagedObjectContext.

Accessing the data via the array controller can be tricky. I've found that array controllers are generally designed to be used with UI elements. There are some tricks that the array controller will use to keep the UI snappy. It will fetch items on a background thread, for instance. Much of this can be configured, but you'll be better off accessing the info doing your own fetch.


The NSArrayController and related classes are intended to serve as off the shelf MVC design controllers. As such their only real function is to link the UI to the data model. If you need to deal with the model otherwise, you usually do so programmatically.

To access the model programmatically, you usually start with a fetch request (NSFetchRequest) to find the appropriate instances of certain entities. Then you would walk the entity relationships to find all other instances of the entities related to the fetched entities.

For example: Suppose you had a schedule type app. You entities are days and events. Each day has several events but each event has only one day.

If you want to check the events for a week, you would fetch the day objects whose date attribute feel in the 7 day range. Then you would ask each day object in turn for its related events.

The iOS does not yet support binding so check out the resources for using Core Data there to see how to manage all this manually.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜