从未保存在Core Data中的数组移动的对象

时间:2012-01-28 07:41:47

标签: objective-c ios core-data

我有一个显示视频的应用程序。下面的代码会获取一个视频列表(使用核心数据),仅将其过滤为以前查看过的视频,然后查找下一个视频并将其添加到视频列表中。

基本上我没有展示每个视频,而只是展示以前观看的视频+您应该查看的视频。

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]; 

除了对todaysVideo对象的任何更改(例如,将其标记为已查看)都没有保存回数据库之外,UI中的所有内容都按预期工作。这是因为我把它移到了另一个阵列吗?

1 个答案:

答案 0 :(得分:1)

是的,这就是您的更改未保存到核心数据中的原因。您正在创建核心数据的本地副本并对其进行修改。这不会反映在核心数据中。将您的代码更改为此代码并查看其是否有效

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];