【问题标题】:Correct way to refresh Core Data database刷新Core Data数据库的正确方法
【发布时间】:2011-02-05 22:16:23
【问题描述】:

我的应用程序已设置为在首次使用时会从基于 Web 的 xml 提要下载所需的数据。

用户还可以选择通过设置定期刷新数据。

当他们这样做时,我想删除现有数据库,然后通过我用于第一次加载的代码重新创建它。

我读到简单地删除数据库不是正确的方法,所以我使用以下方法在加载新数据集之前销毁数据。

- (void)resetApplicationModel {

NSURL *_storeURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: DBSTORE]];
NSPersistentStore *_store = [persistentStoreCoordinator persistentStoreForURL:_storeURL];
[persistentStoreCoordinator removePersistentStore:_store error:nil];
[[NSFileManager defaultManager] removeItemAtPath:_storeURL.path error:nil];

[persistentStoreCoordinator release], persistentStoreCoordinator = nil;
}

但是这不起作用,在执行数据刷新时,它会下载数据但无法将其保存到数据库中,并在控制台中生成以下错误;

这个 NSPersistentStoreCoordinator 没有持久存储。它无法执行保存操作。

刷新数据库的“正确”方法是什么?

【问题讨论】:

    标签: ipad core-data


    【解决方案1】:

    执行此操作的“正确”方法是获取所有对象,删除每个对象,然后保存上下文。 (http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreData/Articles/cdFetching.html)

    - (void) deleteAllEntitiesForName:(NSString*)entityName {
        NSManagedObjectContext *moc = [self managedObjectContext];
        NSEntityDescription *entityDescription = [NSEntityDescription
            entityForName:entityName inManagedObjectContext:moc];
        NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
        [request setEntity:entityDescription];
        NSError *error = nil;
        NSArray *array = [moc executeFetchRequest:request error:&error];
        if (array != nil) {
            for(NSManagedObject *managedObject in array) {
                [moc deleteObject:managedObject];
            }
            error = nil;
            [moc save:&error];
        }
    
    }
    

    然后你可以重新创建你的对象。

    【讨论】:

    • 我认为“if (array == nil)”应该是“if (array != nil)”
    猜你喜欢
    • 1970-01-01
    • 2013-02-20
    • 2012-08-25
    • 2015-05-31
    • 2014-12-20
    • 1970-01-01
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多