核心数据简单无法得到错误

时间:2012-08-19 09:46:55

标签: xcode core-data save

我在xcode中使用coredata,使用了ray wanderlich教程,但是当我尝试声明上下文时它崩溃了 - nsmanagedobjectcontext,无法弄清楚到底是什么问题,请帮忙

我创建了只有一个实体Datum的核心数据模型,并创建了nsManagedObjectSublass文件Datum.h和Datum.m

app delegate未被更改

看起来好像没有创建对象上下文

它崩溃了NSManagedObjectContext * context = [self managedObjectContext] f ...是错误的它是简单的代码,我实际上复制了所有内容并且崩溃了

#import <UIKit/UIKit.h>




@interface Start : UIViewController <UIAlertViewDelegate> {




}



- (void) SaveData;


@property (nonatomic, retain) IBOutlet UILabel *timer;
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;


- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;


@end



#import "Start.h"
#import "Datum.h"


@implementation Start

@synthesize timer;
@synthesize managedObjectContext = __managedObjectContext;
@synthesize managedObjectModel = __managedObjectModel;
@synthesize persistentStoreCoordinator = __persistentStoreCoordinator;




- (void) SaveData {

    NSLog(@"start 1");

    NSManagedObjectContext *context = [self managedObjectContext];

    NSLog(@"start 2");

    Datum *datumcek = [NSEntityDescription
                                      insertNewObjectForEntityForName:@"Datum"
                                      inManagedObjectContext:context];

    NSLog(@"start 3");

    datumcek.snDatum = [NSDate date];



    NSLog(@"start 4");

    NSError *error;
    if (![context save:&error]) {
        NSLog(@"No save: %@", [error localizedDescription]);
    }

}





- (void)viewDidLoad {

            [self SaveData];

    [super viewDidLoad];
}



- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {

    [UIApplication sharedApplication].idleTimerDisabled=NO;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {


    [super dealloc];
}

- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != 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();
        } 
    }
}

#pragma mark - Core Data stack

- (NSManagedObjectContext *)managedObjectContext
{
    if (__managedObjectContext != nil)
    {
        return __managedObjectContext;
    }

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


- (NSManagedObjectModel *)managedObjectModel
{
    if (__managedObjectModel != nil)
    {
        return __managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Start" withExtension:@"momd"];
    __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return __managedObjectModel;
}

/**
 Returns the persistent store coordinator for the application.
 If the coordinator doesn't already exist, it is created and the application's store added to it.
 */
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (__persistentStoreCoordinator != nil)
    {
        return __persistentStoreCoordinator;
    }

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Start.sqlite"];

    NSError *error = nil;
    __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&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. 

         Typical reasons for an error here include:
         * The persistent store is not accessible;
         * The schema for the persistent store is incompatible with current managed object model.
         Check the error message to determine what the actual problem was.


         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.

         If you encounter schema incompatibility errors during development, you can reduce their frequency by:
         * Simply deleting the existing store:
         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]

         * Performing automatic lightweight migration by passing the following dictionary as the options parameter: 
         [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

         Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.

         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }    

    return __persistentStoreCoordinator;
}


#pragma mark - Application's Documents directory

// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}





@end

1 个答案:

答案 0 :(得分:1)

请务必将其添加到- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

中的应用代表中
self.window.rootViewController = self.viewController;
self.viewController.managedObjectContext = self.managedObjectContext;

此外,您应该在app delegate中添加所有这些coreDataStack方法。

不要忘记使用

导入CoreData
#import <CoreData/CoreData.h>

编辑: 抱歉,我意识到您不使用基于视图的应用程序。我认为你不应该在[self saveData]中致电viewDidLoad。只需添加一个快捷按钮或将其添加到viewWillDispear

即可