【发布时间】:2011-11-09 19:41:12
【问题描述】:
这是我的代码:
- (IBAction) saveData
{
NSLog(@"saveData");
[self dismissKeyboard];
Fugitive *job = (Fugitive *)[NSEntityDescription insertNewObjectForEntityForName:@"Fugitive" inManagedObjectContext:managedObjectContext];
job.name = txtName.text;
NSError *error;
// here's where the actual save happens, and if it doesn't we print something out to the console
if (![managedObjectContext save:&error])
{
NSLog(@"Problem saving: %@", [error localizedDescription]);
}
// **** log objects currently in database ****
// create fetch object, this object fetch's the objects out of the database
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Fugitive" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
NSURL *storeURL = [[NSBundle mainBundle] URLForResource:@"iBountyHunter" withExtension:@"momd"];
id globalStore = [[managedObjectContext persistentStoreCoordinator] persistentStoreForURL:storeURL];
[managedObjectContext assignObject:job toPersistentStore:globalStore];
for (NSManagedObject *info in fetchedObjects)
{
NSLog(@"Job Name: %@", [info valueForKey:@"name"]);
}
[fetchRequest release];
[self.navigationController dismissModalViewControllerAnimated:YES];
}
在控制台中我收到此错误:保存时出现问题:操作无法完成。 (可可错误 1570。) 新对象在 tableview 中创建,但未保存,因此在重新启动应用程序时,该对象消失
【问题讨论】:
-
您的核心数据堆栈中可能存在配置问题。在您设置模型、持久存储和上下文的位置发布代码。此外,如果您已将上下文配置为已有商店并且您的应用只有一个商店,则无需执行
assignObject:toPersistentStore:。 -
我已经把代码贴出来了,放在这里太长了