I’m new to Core Data.
In the Data Model I have the entities:
SongPlaylist
This is the relationship:
- Every
Songbelongs to no, one or multiplePlaylist‘s
The I’ve added the relationship to the model like this.
I also made the inverse To-Many Relationship.
Now my question.
The Playlist‘s now have a NSSet with all the Songs.
So I can access them via playlist.songs.
I can fetch any specific Song using a NSPredicate:
- (NSArray *)fetchWithEntity:(NSString *)entity
predicate:(NSPredicate *)predicate
sortDescriptors:(NSArray *)sortDescriptors
error:(NSError **)error {
NSManagedObjectContext *moc = [self managedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription
entityForName:entity
inManagedObjectContext:moc];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];
[request setPredicate:predicate];
[request setSortDescriptors:sortDescriptors];
NSArray *fetchResult = [moc executeFetchRequest:request error:error];
return fetchResult;
}
However, I’d like to be possible to filter the Songs of a specific playlist too, rather than having to filter the NSSet with an NSPredicate, because it’s simply faster.
How can I do this?
The get songs of a specific playlist, just add
"playlist = %@"to the predicate used for fetchingSongobjects, e.g.Or, if the playlist is given by a title:
EDIT If there is a many-to-many relationship between Songs and Playlist, you can define
playlistsas to-many relationship from Song to Playlist, as inverse relationship tosongs. Then the following predicate should work: