我有一个名为TestProject的xcode4项目即将尝试添加CoreData。我添加了一个带有几个实体的数据模型(名为TestDataModel),并为实体创建了NSManagedObject类。
我的问题是我无法加载Persistent Store
if(self.managedObjectContext == nil){
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString* basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
NSURL* storeUrl = [NSURL fileURLWithPath:[basePath stringByAppendingPathComponent: @"TestProject.sqlite"]];
NSError* errors;
NSPersistentStoreCoordinator* persistentStoreCoordinator =
[[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[NSManagedObjectModel
mergedModelFromBundles:nil ]];
if(![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:storeUrl
options:nil
error:&errors])
{
NSLog(@"Error loading persistent store: %@", [errors localizedDescription]);
}
self.managedObjectContext = [[NSManagedObjectContext alloc] init];
[self.managedObjectContext setPersistentStoreCoordinator:persistentStoreCoordinator];
}
我继续收到错误:
Error loading persistant store: The operation couldn’t be completed. (Cocoa error 258.)
请注意我也在模拟器中运行它。
提前致谢。
答案 0 :(得分:1)
您使用的是错误的目录。
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
^^^^^^^^^^^^^^^^^^^^^^^^
将此更改为
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
^^^^^^^^^^^^^^^^^^^
NSDocumentDirectory由iOS创建,但NSDocumentationDirectory目录不是。
答案 1 :(得分:0)
想出来。没意识到我需要创建数据库
代码下方
if(self.managedObjectContext == nil){
NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"TestProject.sqlite"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:storePath]) {
NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"TestProject" ofType:@"sqlite"];
if (defaultStorePath) {
[fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL];
}
}
NSURL *storeUrl = [NSURL fileURLWithPath:storePath];
NSError* errors;
NSPersistentStoreCoordinator* persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[NSManagedObjectModel mergedModelFromBundles:nil]];
if(![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&errors])
{
NSLog(@"Error loading persistent store: %@", [errors localizedDescription]);
}
self.managedObjectContext = [[NSManagedObjectContext alloc] init];
[self.managedObjectContext setPersistentStoreCoordinator:persistentStoreCoordinator];
}
你还需要这个
- (NSString *)applicationDocumentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}