你需要这样的东西:
- (void)copyPreparedDatabase{
__persistentStoreCoordinator = nil;
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"DATABASE.sqlite"];
NSString *storePath = [storeURL path];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"DATABASE" ofType:@"sqlite"];
if (defaultStorePath) {
NSError *error = nil;
if ([fileManager fileExistsAtPath:storePath]) {
[fileManager removeItemAtPath:storePath error:&error];
}
[fileManager copyItemAtPath:defaultStorePath toPath:storePath error:&error];
NSDictionary *fileAttributes = [NSDictionary dictionaryWithObject:NSFileProtectionComplete forKey:NSFileProtectionKey];
if (![[NSFileManager defaultManager] setAttributes:fileAttributes ofItemAtPath:storePath error:&error]) {
}
}
}
然后你从 AppDelelate.m 中的 - (NSPersistentStoreCoordinator *)persistentStoreCoordinator 调用它
建议:做一些自定义开关,如#define IMPORT_PREPARED_DATABASE
这样做: if (![fileManager fileExistsAtPath:storePath] && !IMPORT_PREPARED_DATABASE) { //&& 1==2 [self copyPreparedDatabase];
}
所以你可以控制何时构建新的准备好的数据库或何时使用现有的....
注意:当你建立新的准备好的数据库sto模拟器时,复制数据库并将其粘贴到旧的...