user3195388
user3195388

Reputation: 129

Access related objects in Core Data

I've made a relationship between my Songs and Playlists entities. Now I'm trying to access the Songs in the selected Playlist. The selected playlist is saved in the object

optionsSingle.selectedRowNumber

I have this fetch method where I'm accessing all the songs object and save them in a NSMutableArray called playlists. How do I only fetch the songs which are related to the give playlist object (optionsSingle.selectedRowNumber)?

- (void)fetchDevices {

    NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Playlists"];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Playlists" inManagedObjectContext:managedObjectContext];
    [fetchRequest setEntity:entity];    

    playlists = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
}

Core Data Model:

enter image description here

Upvotes: 0

Views: 99

Answers (2)

Sebastian Wramba
Sebastian Wramba

Reputation: 10127

There are some issues with your code and model. Entity classes should be named singular (Song and Playlist).

The method is called fetchDevices (seems like a copy&paste error and should rather be fetchPlaylists or something?)

You are doing too much to retrieve them. The method can be reduced to:

- (void)fetchPlaylists {

    NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Playlist"];    

    playlists = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
}

You can also try to reduce the relation so that one Playlist has many Song(s). That should be enough for your requirements. Then you can proceed and access a list of songs that will automatically be fetched with your playlist.

Upvotes: 1

Mundi
Mundi

Reputation: 80271

I think you have a better design choice. While the corrections suggested by Sebastian are very important, you should redesign your table view. (I infer it is a table view displaying your playlists from your question).

You should use a NSFetchedResultsController rather than creating an array and populating your table with the contents of the array. The FRC will take care of all the fetching and memory management specific for the table view.

You can get a working example of a NSFetchedResultsController easily by opening the master-detail template ("New Project" in Xcode) and checking the "Core Data" option.

Now you can get to the playlist very easily:

Playlist *playlist = [self.fetchedResultsController objectAtIndexPath:indexPath]; 

You will find that it will be much easier to write clean, concise and readable code.

Upvotes: 2

Related Questions