所以,我终于让Core Data按预期工作了。保存内容,并将其加载到UITableView子类中。只要应用程序正在运行或在后台运行,它就能完美运行。
但是一旦应用终止(未卸载)并重新打开,数据就会丢失,或者更改为无效(当我将NSManagedObjects加载到我的阵列时,我仍然得到正确的数量 - 属性只是无)...
我将上下文保存在:
- (void)applicationDidEnterBackground:(UIApplication *)application
除此之外,App-Delegate是100%核心数据样板代码,方法除外:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
我可以粘贴一些代码,但我不知道什么可能有趣......
有什么建议吗?
---------- ---------- EDIT
保存新实例的代码:
// create new screenshot and save
ScreenshotInfo *newScreenshot = [NSEntityDescription insertNewObjectForEntityForName:@"ScreenshotInfo" inManagedObjectContext:managedObjectContext];
newScreenshot.date = [[NSDate date] timeIntervalSince1970];
newScreenshot.note = @"click to add note...";
newScreenshot.thumbnailData = [self createThumbnailDataFromImage:image];
PicForScreenshot *newPic = [NSEntityDescription insertNewObjectForEntityForName:@"PicForScreenshot" inManagedObjectContext:managedObjectContext];
newScreenshot.pic = newPic;
newPic.image = screenshotData;
newPic.info = newScreenshot;
NSError *error;
if (![managedObjectContext save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
加载代码:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"ScreenshotInfo" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSError *error;
pics = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (!pics) {
[NSException raise:@"Fetch failed" format:@"reAson: %@",[error localizedDescription]];
}
填充tableViewCells的代码:
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
CellView *cell = [tableView dequeueReusableCellWithIdentifier:@"CellView"];
ScreenshotInfo *currentPic = [pics objectAtIndex:indexPath.row];
[[cell image]setImage:[UIImage imageWithData:currentPic.thumbnailData]];
[[cell noteLabel]setText:currentPic.note];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:currentPic.date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/yyyy hh:mma"];
[[cell dateLabel]setText:[dateFormatter stringFromDate:date]];
return cell;
}
这应该是有趣的代码..
实例创建并保存在一个ViewController中,并加载到另一个(UITableViewController)。
@Tommy,你说你确定保存在某种程度上是错误的,但是如果保存不正确,TableView如何在创建后立即正确获取它。