Reputation: 35
I have an application that displays videos. The code below gets a list of videos (using core data), filters it to only the videos that have been viewed before, and then finds the next video and adds it to the list of videos.
Basically instead of showing every video I am just showing the previously viewed videos + the one you should view next.
videos = [[loader loadVideos] mutableCopy];
// Get only the viewed videos
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(viewed == YES)"];
NSMutableArray *viewedVideos = [[videos filteredArrayUsingPredicate:predicate] mutableCopy];
Video *lastWatchedVideo = [viewedVideos lastObject];
// The next video will be equal to the video order of the previous video (starting at 1 vs 0)
Video *todaysVideo = [videos objectAtIndex:[lastWatchedVideo.videoOrder intValue]];
[viewedVideos addObject:todaysVideo];
Everything is working as expected in the UI, except any changes to the todaysVideo object (e.g. marking it as viewed) are not being saved back to the database. Is this because I have moved it to another array?
Upvotes: 2
Views: 126
Reputation: 2830
Yes, that is why your changes are not being saved into the core data. You are creating a local copy of the core data and modifying it. This will not be reflected in the core data. Change your code to this and see if it works
videos = [loader loadVideos];//You get the videos from core data
// Get only the viewed videos
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(viewed == YES)"];
NSMutableArray *viewedVideos = [videos filteredArrayUsingPredicate:predicate];
Video *lastWatchedVideo = [viewedVideos lastObject];
// The next video will be equal to the video order of the previous video (starting at 1 vs 0)
Video *todaysVideo = [videos objectAtIndex:[lastWatchedVideo.videoOrder intValue]];
todaysVideo.viewed=YES;
//Now that you have modified it save the context
NSError *error=nil;
[context save:&error];
Upvotes: 1