Ios 将CoreData添加到现有项目时出错

Ios 将CoreData添加到现有项目时出错,ios,objective-c,cocoa,core-data,Ios,Objective C,Cocoa,Core Data,这是代码 #import "AppDelegate.h" #import "Crittercism.h" @interface AppDelegate () @end @implementation AppDelegate @synthesize managedObjectContext = _managedObjectContext; @synthesize managedObjectModel = _managedObjectModel; @synthesize pe

这是代码

        #import "AppDelegate.h"
#import "Crittercism.h"
@interface AppDelegate ()


@end

@implementation AppDelegate

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

   id context =  self.managedObjectContext;

    return YES;
}

#pragma mark - Core Data stack


- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "Sceram-17.test_core" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CSDCoreData" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (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:@"Models/CSDCoreData.sqlite"];
    //NSURL* storeURL = [[NSBundle mainBundle] URLForResource:@"CSDCoreData" withExtension:@"sqlite"];
    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;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation 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();
        }
    }
}



@end
和错误:

2015-05-23 12:36:17.339《网络安全文摘》[6550:799489]核心数据:错误:-addPersistentStoreWithType:SQLite配置:(null)URL:file:///Users/Scream/Library/Developer/CoreSimulator/Devices/A9D94FFA-7DFA-441C-8811-D4FB0ECC54E9/data/Containers/Data/Application/59B0108B-6019-456A-A62D-0FD8A60ED580/Documents/Models/CSDCoreData.sqlite 选项:(null)…返回错误Domain=NSCOCAERRORDOMAIN Code=512“操作无法完成。(Cocoa错误512.)“UserInfo=0x7f8a21df8370{reason=无法创建文件;Code=2}使用UserInfo字典{ reason=“创建文件失败;代码=2”; } 2015-05-23 12:36:17.340 CyberSecurityDigest[6550:799489]未解决的错误域=您的错误域代码=9999“未能初始化应用程序保存的数据”用户信息=0x7f8a21daa7a0{NSLocalizedFailureReason=创建或加载应用程序保存的数据时出错,NSLocalizedDescription=初始化应用程序保存的数据失败,NSUnderlyingError=0x7f8a21df9270“操作无法完成。(Cocoa错误512.)”{ NSLocalizedDescription=“未能初始化应用程序保存的数据”; NSLocalizedFailureReason=“创建或加载应用程序保存的数据时出错。”; NSUnderlyingError=“Error Domain=nscocaerorrordomain Code=512\”该操作无法\U2019t完成。(Cocoa错误512)。\“UserInfo=0x7f8a21df8370{reason=Failed to create file;Code=2}”; }

我已将CSDCoreData.xcdatamode添加到目录模型。创建了pch文件并导入了核心数据。使用此方法重新安装

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator 


// Create the coordinator and store

_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
更改为:

    NSError *err;
if ([[NSFileManager defaultManager] createDirectoryAtURL:[[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Models/"] withIntermediateDirectories:YES attributes:nil error:&err])
{
   NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Models/CSDCoreData.sqlite"];
}
else
{
    NSLog(@"Something wrong: %@",err.localizedDescription);
    abort();
}

 // In this position.

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;
}