How to Store a Mixed Array in Core Data
I need to store two types of objects, Feed
and Folder
, in an array in Core Data. For example:
Array
Feed
Feed
Folder
Feed
Folder
Folder
…etc...
I know about BWOrderedManagedObject
for storing objects in order in Core Data, but I'm no开发者_高级运维t sure how to store mixed objects (the array needs to be mixed, since the items are in a specific order). Ideally, I'd have a relationship that pointed to two entities, but obviously this isn't possible.
The only solution I can see is to make the array a Transformable
attribute. However, what about the objects stored within the array? Will I need to manage all of them myself or will they still be managed by Core Data?
Here's how I've done it:
alt text http://gallery.me.com/davedelong/100084/Screen%20shot%202010-07-06%20at%207.22.10%20PM/web.png?ver=12784658050001
AbstractListItem
is an abstract entity that has the order property and a relationship to a Folder
, which indicates the item's (single) parent.
Folder
is a concrete child of AbstractListItem
that has a to-many relationship to AbstractListItem
, which means the folder can have as many children as it wants that are AbstractListItems
(so either Folders
or Feeds
).
Feeds
aren't anything special, except that they also inherit from AbstractListItem
(meaning that they have an order and a parent, and can be children of a Folder
).
So once you have a folder, you can get all of its children in order by doing something like:
NSArray * orderedChildren = [[aFolder children] sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"order" ascending:YES]]];
To get your top-level items, you'd execute a fetch looking for all AbstractListItem
objects where parent = nil
.
精彩评论