【发布时间】:2014-04-17 23:17:35
【问题描述】:
按照本教程http://www.raywenderlich.com/12170/core-data-tutorial-how-to-preloadimport-existing-data-updated,我创建了一个空的命令行应用程序,使用核心数据播种数据库,随后我将其移动(通过 quizgeodata.sqlite 文件)到我正在构建的 ios 应用程序中。教程列出的使它工作的唯一其他步骤是将此代码添加到应用程序委托中的 persistantStoreCoordinator
if (![[NSFileManager defaultManager] fileExistsAtPath:[storeURL path]]) {
NSURL *preloadURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"quizgeodata" ofType:@"sqlite"]];
NSError* err = nil;
if (![[NSFileManager defaultManager] copyItemAtURL:preloadURL toURL:storeURL error:&err]) {
NSLog(@"Oops, could copy preloaded data");
}
}
(之前的步骤包括将类文件(对应于实体)和 ...xcdatamodel.d 文件放入空的命令行应用程序中,以确保模式相同)。当我在空的命令行应用程序中运行代码时,它显示了我在日志语句中导入的获取数据,所以我假设通过将quizgeodata.sqlite 复制回 ios 应用程序并在持久存储中添加那一点代码协调器,那么下面的代码(在 viewDidLoad 中)应该从核心数据中获取数据,但是日志语句显示没有数据被检索。下面代码中的错误日志显示为“null”(我假设没有错误),当我要求 xCode 打印 sql 语句时,它会在控制台中显示这一点
2014-04-17 16:11:57.477 qbgeo[767:a0b] CoreData: annotation: total fetch execution time: 0.0026s for 0 rows.
很明显,我复制的 sqlite 文件中没有数据。你能解释一下我可能需要做什么才能让它工作吗?
请注意,我运行了 Project > Clean 几次,所以这不是问题
来自 ViewDidLoad id 委托 = [[UIApplication sharedApplication] 委托]; self.managedObjectContext = [委托 managedObjectContext];
NSError *error;
if (![self.managedObjectContext save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"Sportsquiz" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSLog(@"error %@", [error description]);
NSArray *messedUpObjects = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
for (Sportsquiz *info in messedUpObjects) {
NSLog(@"correctAnswer %@", [info valueForKey:@"question"]);
NSLog(@"correctAnswer %@", [info valueForKey:@"correctAnswer"]);
}
【问题讨论】:
-
要将 SQLite 文件从一个项目复制到另一个项目,请复制它。然后您需要使用 Xcode 的接口将其添加到目标项目中。然后你需要告诉 Xcode 它将被包含在构建中。然后,您需要添加启动逻辑以在首次启动时将文件从捆绑包复制到设备上的读/写存储。
标签: ios objective-c core-data