This is structure of coredata architecture.
After adding entries to 'Artists', using them to newly added 'Album' entries is working perfect.
But the problem is as shown in img- 2 & 3, after assigning the 'michael jackson' to 'Insomniac 2010' album & then adding the same artist to 'Baby ft ludacris' losing the reference from the album 'Insomniac'.
This is the code where I save the context in AlbumDetailViewController.h
- (void)EntityRecordstableview:(UITableView *)tableView didselectrowatindexpath:(NSIndexPath *)indexPath forentity:(id)entity
{
Artist *selectedArtist = entity;
UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
[cell setSelected:NO animated:YES];
if ([self.pickedArtists containsObject:selectedArtist]) {
[self.pickedArtists removeObject:selectedArtist];
[cell setAccessoryType:UITableViewCellAccessoryNone];
editingAlbum.artist = self.pickedArtists;
[self saveTheContext:editingAlbum.managedObjectContext];
// NSLog(@"%d",self.pickedArtists.count);
}
else {
[self.pickedArtists addObject:selectedArtist];
[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
editingAlbum.artist = self.pickedArtists;
[self saveTheContext:editingAlbum.managedObjectContext];
// NSLog(@"%d",self.pickedArtists.count);
}
}
I think there must be some problem in managedObjectContext saving. Is it should be like this
self.managedObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
[self saveTheContext:self.managedObjectContext];
instead of
[self saveTheContext:editingAlbum.managedObjectContext];
I tried this but this is also failing to work as per expectations.
I have updated your code. Please check for the same. Their is a problem in relationship between Artist & Album. It must be Many to Many.
Your relationship between Album & Artist is 1 to many. Hence, if you will select Artist for multiple Album then it will override its value. Please check your database for same.
Code : Click Here