2009-01-30 39 views
0

我在这里有一个CoreData应用程序(无文档),1个实体和1个tableview用于编辑/添加/删除实体的实例。现在我可以手动添加和保存,但我想CoreData-apps中的“保存”

a)保存全自动改变
b)加上全自动一些“情况”与第一次启动。

我认为a)可以用NSNotifications解决。但是哪些实体使用?

任何想法如何解决a)b)

谢谢你every回答。 =)

回答

1

自动保存可能会有点棘手比你首先想到有时,因为有可能是当你的应用程序数据处于无效状态(例如,当用户正在编辑的实体),要么不能保存或保存是没有意义的。不幸的是,不容易setAutosaves:YES财产,所以你必须自己实现它。使用通知某些动作后,以节省是做这件事,你也可以设置一个计时器,定期保存,如果它是有道理的,你的应用程序。

要填充一个空的数据文件,只需在启动时检查数据存储区是否为空(applicationDidFinishLaunchingawakeFromNib是两个可能的位置),并且它正常插入一些实体。唯一棘手的部分是在此过程中禁用撤消管理。下面是我的一个应用程序示例:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification; 
{  
    NSURL *fileURL = [NSURL fileURLWithPath:[self.applicationSupportFolder stringByAppendingPathComponent:WLDataFileName]]; 

    NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];  
    NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model]; 
    NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init]; 
    NSFetchRequest *request = [[NSFetchRequest alloc] init]; 

    [coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:fileURL options:nil error:NULL]; 
    [context setPersistentStoreCoordinator:coordinator]; 
    [request setEntity:[NSEntityDescription entityForName:@"Shelf" inManagedObjectContext:context]]; 

    if ([context countForFetchRequest:request error:NULL] == 0) 
     [self _populateEmptyDataStore:context]; 

    _managedObjectContext = [context retain]; 

    [request release]; 
    [coordinator release]; 
    [context release]; 

    // finish loading UI, etc... 
} 

- (void)_populateEmptyDataStore:(NSManagedObjectContext *)context; 
{ 
    [[context undoManager] disableUndoRegistration]; 

    WLSmartShelfEntity *allItems = [NSEntityDescription insertNewObjectForEntityForName:@"SmartShelf" inManagedObjectContext:context]; 
    WLSmartShelfEntity *trash = [NSEntityDescription insertNewObjectForEntityForName:@"SmartShelf" inManagedObjectContext:context]; 

    allItems.name = NSLocalizedString(@"All Items", @""); 
    allItems.predicate = [NSPredicate predicateWithFormat:@"isTrash = FALSE"]; 
    allItems.sortOrder = [NSNumber numberWithInteger:0]; 
    allItems.editable = [NSNumber numberWithBool:NO]; 

    trash.name = NSLocalizedString(@"Trash", @""); 
    trash.predicate = [NSPredicate predicateWithFormat:@"isTrash = TRUE"]; 
    trash.sortOrder = [NSNumber numberWithInteger:2]; 
    trash.editable = [NSNumber numberWithBool:NO]; 

    [context processPendingChanges]; 
    [[context undoManager] enableUndoRegistration]; 

    DebugLog(@"Filled empty data store with initial values."); 
} 
0

有关于自动保存和核心数据的苹果邮件列表看看this thread

+0

AFAICS,该链接无用 - 它指的是一个线程,其中包含零信息。 – Adam 2011-05-08 21:25:30