为什么Core Data不会将这些更改持久化到磁盘?

时间:2010-05-03 07:41:40

标签: iphone core-data

我在我的模型中添加了一个新实体,它加载正常,但内存中的更改不会持久保存到磁盘。我在汽车对象上设置的值在内存中工作正常,但在按下主页按钮时(在模拟器中)不会持久保存到磁盘。我在我的应用程序中的另一个实体上使用几乎完全相同的代码,并且其值保持在磁盘上(核心数据 - > sqlite3);有没有人知道我在这里俯瞰什么? Car是托管对象,汽车对象的NSMutableArray中的汽车和Car是实体,Visible是我试图设置的实体的属性。 谢谢你的帮助。 斯科特

- (void)viewDidLoad {
   myAppDelegate* appDelegate = (myAppDelegate*)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext* managedObjectContex = appDelegate.managedObjectContext;
    NSFetchRequest* request = [[NSFetchRequest alloc] init];
    NSEntityDescription* entity = [NSEntityDescription entityForName:@"Car" inManagedObjectContext:managedObjectContex];
    [request setEntity:entity];

    NSSortDescriptor* sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Name" ascending:YES];
    NSArray* sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];

    [request setSortDescriptors:sortDescriptors];

    [sortDescriptors release];
    [sortDescriptor release];

    NSError* error = nil;
    cars = [[managedObjectContex executeFetchRequest:request error:&error] mutableCopy];

    if (cars == nil) {
        NSLog(@"Can't load the Cars data! Error: %@, %@", error, [error userInfo]);
    }


    [request release];

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath {
    Car* car = [cars objectAtIndex:indexPath.row];

    if (car.Visible == [NSNumber numberWithBool:YES]) {
        car.Visible = [NSNumber numberWithBool:NO];
        [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryNone;
    }
    else {
        car.Visible = [NSNumber numberWithBool:YES];
        [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;

    }

    }

以下是我的持久性商店协调员选项:

persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSDictionary* options =  [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithBool:YES],
                    NSMigratePersistentStoresAutomaticallyOption, 
                         [NSNumber numberWithBool:YES], 
                         NSInferMappingModelAutomaticallyOption, nil];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error]) {

}    

3 个答案:

答案 0 :(得分:2)

当您向应用程序的托管对象上下文添加新实体时,您必须使用托管对象上下文的-save:方法来保存这些更改。

我强烈建议您阅读Apple的Core Data Programming Guide,了解核心数据对象和方法,以及如何创建,保存,删除和修改实体。

答案 1 :(得分:1)

我在这一棵树上完全咆哮着。

帮助我发现问题的原因是使用此执行参数打开核心数据跟踪:-com.apple.CoreData.SQLDebug 1

原来我在选择如何显示可见值(我没有发布代码)时遇到了逻辑问题,这导致了错误。核心数据正在做正确的事情,只有在值不同时才写出更改,但我无法分辨,因为我显示的值不正确。

答案 2 :(得分:0)

我怀疑Alex有正确的答案,但您可以发布显示创建 NSManagedObject的代码吗?

更新

然后Alex是对的,你没有保存数据。由于您说您添加了保存例程,因此共享该代码。

相关问题