Frage

I'm creating an app and I'm storing the data using core data. It works fine but I was wondering what's the best way to return a sorted array from an set ?

For example, I have an entity A (Button) that contains a list of entity B (Image). As we all know core data is storing the to-many relationship using an NSSet. But I want to keep track of the initial order so I added a property "order" for that purpose. The problem is that in my code I need the list of images sorted so in a category file (Button+Create) I created a method like this one :

- (NSArray*)imagesArray
{
    return [self.images sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDeacriptorWithKey:@"order" ascending:YES]]];
}

But I don't think that's the best way to do because if a need to access this list from multiple area in my code (different classes) then I need to sort the set x times ... Is there a way to add an array (property) in my category in order to sort once and then only retrieve the property ?

What are your thoughts about that ?

Thanks

War es hilfreich?

Lösung

You can add properties to categories: http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/ObjectiveC/Chapters/ocAssociativeReferences.html

Here is another example:

How to add properties to NSMutableArray via category extension?

But

Be aware that you will be responsible to observe changes (e.g. via KVO) to the initial coredata NSSet property.
So if changes occur you have to "recalculate" your property properly...
If your target was iOS 5.0 or higher, I would recommend to use Ordered Sets, but due to the fact that you are not, I could imagine using the way described in the links above

Andere Tipps

I think your approach with order property is correct. I'd rather create a method in my model something like -(NSArray *)sortedItems which would have an NSFetchRequest with appropriate sort descriptor. If you want you can cache the result - save this array in memory. Your NSManagedObject can also have properties that are not stored in the database, just in memory. But I really don't think this is necessary considering the speed and performance of Core Data.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top