Search code examples
iphoneiosipadcore-datansset

iOS / Core Data - Best way to return an array from a NSSet relationship?


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


Solution

  • 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