0

xcode で coredata を使用しています。レイ ワンダーリッヒ チュートリアルを使用しましたが、コンテキストを宣言しようとするとクラッシュします - nsmanagedobjectcontext、一体何が間違っているのかわかりません。助けてください

エンティティ Datum が 1 つだけのコア データ モデルを作成し、nsManagedObjectSublass ファイル Datum.h および Datum.m を作成しました。

アプリのデリゲートは変更されていません

オブジェクトコンテキストが作成されていないようです

それは 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
4

1 に答える 1

1

これをアプリのデリゲートに必ず追加してください- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

self.window.rootViewController = self.viewController;
self.viewController.managedObjectContext = self.managedObjectContext;

また、これらすべての coreDataStack メソッドをアプリ デリゲートに追加する必要があります。

CoreData をインポートすることを忘れないでください

#import <CoreData/CoreData.h>

編集: 申し訳ありませんが、ビュー ベースのアプリケーションを使用していないことに気付きました。[self saveData]電話をかけるべきではないと思いますviewDidLoad。クイックボタンを追加するか、追加するだけですviewWillDispear

于 2012-08-19T09:57:42.267 に答える