0

为了在第一次启动时在我的应用程序中预填充 CoreData,我包含了一个 PreModel.sqlite 文件,该文件以前由应用程序从它从 Web 服务下载的数据中创建,其中包括图像。

为了填充模型,我这样做:

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{    
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }

    NSLog(@"creating new store");

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"PreModel.sqlite"];

    if(![[NSFileManager defaultManager] fileExistsAtPath:[storeURL path]]) {

        NSString *sqlitePath = [[NSBundle mainBundle] pathForResource:@"PreModel" ofType:@"sqlite"];
        if (sqlitePath) {
            NSError *error = nil;
            [[NSFileManager defaultManager] copyItemAtPath:sqlitePath toPath:[storeURL path] error:&error];
            if (error) {
                NSLog(@"Error copying sqlite database: %@", [error localizedDescription]);
            }
        }
    }     

    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {

        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }   

    return _persistentStoreCoordinator;
}

它似乎工作。但我有两个问题:

  1. 如果 sqlite 文件只是一个数据库文件并且实际上不包含任何图像,那么应用程序如何在首次启动时查找和加载图像?
  2. 即使在应用程序的后续运行中,我每次都会看到“创建新商店”记录。为什么_persistentStoreCoordinator总是零?我清楚地在代码中设置它。
4

1 回答 1

0
  1. 可以将图像存储在数据库文件中,通常作为二进制 blob(看起来像 Core Data 中的 NSData 实例)。如果您可以提供有关您的模型或存储/加载图像的代码的更多信息,我们可以更具体。
  2. 在这种情况下,每次启动应用程序时,都会记录创建新商店” 。尽管 SQLite 文件在磁​​盘上是持久的,但您不能期望代码中的数据结构在应用程序终止时仍然存在 - 您需要在程序每次启动时为其创建一个新的持久存储对象。

    Think of it like assigning NSInteger x = 10, then expecting to be able to quit and relaunch your program while maintaining that x has the value 10. That's not how programs work - you'd need to reassign x = 10 before you can expect to read x and get 10 back. The variable _persistentStoreCoordinator works the same way here.

于 2012-09-07T17:08:32.930 回答