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

时间:2015-05-23 09:43:42

标签: ios objective-c cocoa core-data

这是代码

        #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 Cyber​​SecurityDigest [6550:799489] CoreData:错误:-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 options:(null)...返回错误Error Domain = NSCocoaErrorDomain Code = 512“操作无法完成。(Cocoa error 512.)”UserInfo = 0x7f8a21df8370 {reason =创建文件失败; userInfo字典的代码= 2} {       reason =“创建文件失败;代码= 2”;   }   2015-05-23 12:36:17.340 Cyber​​SecurityDigest [6550:799489]未解决的错误错误域= YOUR_ERROR_DOMAIN代码= 9999“无法初始化应用程序的已保存数据”UserInfo = 0x7f8a21daa7a0 {NSLocalizedFailureReason =创建或加载应用程序已保存时出错data。,NSLocalizedDescription =无法初始化应用程序保存的数据,NSUnderlyingError = 0x7f8a21df9270“操作无法完成。(Cocoa error 512.)”},{       NSLocalizedDescription =“无法初始化应用程序保存的数据”;       NSLocalizedFailureReason =“创建或加载应用程序保存的数据时出错。”;       NSUnderlyingError =“Error Domain = NSCocoaErrorDomain Code = 512 \”操作无法完成。 (可可错误512。)\“UserInfo = 0x7f8a21df8370 {reason =创建文件失败;代码= 2}”;   }

我已将CSDCoreData.xcdatamode添加到目录模型中。创建了pch文件并导入了Core Data。重新安装

1 个答案:

答案 0 :(得分:0)

在这种方法中,

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

}