2

My core data model:

Playlist
=======
name

songs (to-many relationship to Song objects, NSOrderedSet)

A playlist has multiple songs, and the song order is important.
Using NSOrderedSet I can keep the songs order, the problem is when I want to fetch and present a playlist's songs in a table view, I don't know how to use that advantage with a NSFetchRequest.

This is how I fetch playlist's songs:

NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Song"];
request.predicate = [NSPredicate predicateWithFormat:@"ANY playlists = %@", self.playlist];
request.sortDescriptors = // ???
request.fetchBatchSize = 20;

self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
                                                                    managedObjectContext:managedObjectContext
                                                                      sectionNameKeyPath:nil
                                                                               cacheName:nil];  

Actually this won't work because the NSFetchedResultsController requires a fetch request with sort descriptors.

So I have the songs order, but I can't fetch them according to that order?

Mario
  • 2,431
  • 6
  • 27
  • 34

2 Answers2

0

I don't think this is possible, you will need to store the sort order in some other way. Here is a discussion about it: NSFetchedResultsController and NSOrderedSet relationships

Community
  • 1
  • 1
Patrick Tescher
  • 3,387
  • 1
  • 18
  • 31
-1

I've done this in the past:

Add this method to your Song NSManagedObject subclass:

- (NSUInteger)indexInPlaylist
{
    NSUInteger index = [self.playlist.songs indexOfObject:self];
    return index;
}

Then you can use this method in your sort descriptor for your NSFetchedResultsController:

fetchRequest.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"indexInPlaylist" ascending:YES]];
random
  • 8,568
  • 12
  • 50
  • 85
  • Then your song relationship is a many-to-many, to be completely honest I've never tried it with that setup. – random Feb 20 '14 at 17:17
  • 1
    That does not work if core data is SQL backed up, I'm getting the followign error: keypath indexInPlaylist not found in entity – Marián Černý Sep 12 '14 at 11:40