谁能告诉我下面的代码有什么问题吗? 它总是在包含“addPersistentStoreWithType”的行处崩溃。
欢迎任何建议。
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
// Create the coordinator and store
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Core_Data.sqlite"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:[storeURL path]]) {
NSURL *defaultStoreURL=[[NSBundle mainBundle] URLForResource:@"Core_Data" withExtension:@"sqlite"];
if (defaultStoreURL) {
// By default we use what is in the bundle read-only.
storeURL=defaultStoreURL;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![fileManager fileExistsAtPath:[storeURL path]])
NSLog(@"RO-DB NOT FOUND");
else NSLog(@"RO-DB FOUND");
NSError *error = nil;
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:storeURL
options:@{NSSQLitePragmasOption:@{ @"journal_mode":@"DELETE" },
NSReadOnlyPersistentStoreOption:[NSNumber numberWithBool:YES]}
error:&error]) {
NSLog(@"RO-DB NOT OPENED");
}
return _persistentStoreCoordinator;
}
}
NSError *error = nil;
NSString *failureReason = @"There was an error creating or loading the application's saved data.";
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
// Report any error we got.
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
dict[NSLocalizedFailureReasonErrorKey] = failureReason;
dict[NSUnderlyingErrorKey] = error;
error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
其余的代码只不过是 Xcode 在使用具有核心数据的单 View 模板构建新项目时生成的代码。
最佳答案
您不能添加 bundle 中的读写存储。该包是只读的。
相反,先将 sqlite 文件复制到文档目录,然后使用该 URL 将商店添加到商店协调器。
我认为 journal_mode "delete"和 NSReadOnlyPersistentStoreOption
不兼容。 (无论如何,这似乎没有任何意义。)也许 journal_mode“关闭”或没有 journal_mode 选项更有希望。
关于ios - persistenceStoreCoordinator 有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27283970/