managedObjectContext是零...不知道发生了什么

时间:2012-07-07 15:15:39

标签: iphone objective-c ios xcode core-data

我有一个现有的项目,我正在添加CoreData框架,但我遇到了一些麻烦。我之前已经将CoreData添加到现有项目中,但我不确定在这种情况下我哪里出错了。

我已将所有必要的代码添加到AppDelegate.h和.m文件中。我已将import语句添加到我的.pch中。我已经使用Lesson对象的所有属性创建了我的数据模型文件。我已经做了我能想到的一切,但是当我的viewDidLoad方法运行时,我的managedObjectContext仍然是零。

我已经在下面发布了我的AppDelegate和我的ViewController的代码。希望有人能就我出错的地方提供一些建议。谢谢:))

AppDelegate.h

#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

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

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

@end

AppDelegate.m

#import "AppDelegate.h"

@implementation AppDelegate

@synthesize window = _window;
@synthesize managedObjectContext = __managedObjectContext;
@synthesize managedObjectModel = __managedObjectModel;
@synthesize persistentStoreCoordinator = __persistentStoreCoordinator;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

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

// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)managedObjectContext
{
    if (__managedObjectContext != nil) {
        return __managedObjectContext;
    }

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

// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
- (NSManagedObjectModel *)managedObjectModel
{
    if (__managedObjectModel != nil) {
        return __managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"iLessonsPiano" 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:@"iLessonsPiano.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

ViewController.h

#import <UIKit/UIKit.h>
#import "Lesson.h"
#import "PDFViewController.h"
#import "MediaPlayer/MediaPlayer.h"
#import "PracticeViewController.h"

@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) NSManagedObjectContext* managedObjectContext;

// Array to hold all lessons.

@property (nonatomic, strong) NSMutableArray *lessonLibrary;

// Array to hold the purchased lessons.

@property (nonatomic,strong) NSMutableArray *purchasedLessons;

// Lesson detail display items.

@property (strong, nonatomic) IBOutlet UIImageView *coverArt;
@property (weak, nonatomic) IBOutlet UILabel *lessonTitle;
@property (weak, nonatomic) IBOutlet UILabel *lessonSubtitle;
@property (weak, nonatomic) IBOutlet UILabel *timingLabel;
@property (weak, nonatomic) IBOutlet UILabel *keySignatureLabel;
@property (weak, nonatomic) IBOutlet UIImageView *difficultyImage;
@property (weak, nonatomic) IBOutlet UITextView *descriptionTextView;
@property (weak, nonatomic) IBOutlet UIImageView *dividerImage;
@property (weak, nonatomic) IBOutlet UIImageView *detailBackgroundImage;
@property (weak, nonatomic) IBOutlet UIImageView *detailsImage;

@property (strong, nonatomic) IBOutlet UITableView *tableView;


//Table Methods

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;

// Variables and Methods for the Video Player

@property (strong, nonatomic) MPMoviePlayerViewController *player;

@end

ViewController.m

#import "ViewController.h"
#import "AppDelegate.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize coverArt;
@synthesize lessonTitle;
@synthesize lessonSubtitle;
@synthesize timingLabel;
@synthesize keySignatureLabel;
@synthesize difficultyImage;
@synthesize descriptionTextView;
@synthesize dividerImage;
@synthesize detailBackgroundImage;
@synthesize detailsImage;
@synthesize purchasedLessons;
@synthesize tableView;
@synthesize player;
@synthesize managedObjectContext;
@synthesize lessonLibrary;

//TABLE METHODS

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return purchasedLessons.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    // Create a cell.
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"purchased"];

    // Populate the cell with data.
    Lesson *temp = [[Lesson alloc] init];
    temp = [purchasedLessons objectAtIndex:indexPath.row];
    cell.textLabel.text = temp.title;
    cell.detailTextLabel.text = temp.subtitle;

    // Return the cell.
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    // Determine what row is selected and retrieve the correct Lesson object.
    Lesson *currentSelection = [[Lesson alloc] init];
    int row = [indexPath row];
    currentSelection = [purchasedLessons objectAtIndex:row];
    if (currentSelection.purchaseStatus == 1) {
        UIImage *tempCoverArt = [UIImage imageNamed:currentSelection.coverArtFilename];
        UIImage *tempDifficulty = [UIImage imageNamed:currentSelection.difficultyImageFilename];

        // Change the information in the details pane to the details for the current lesson.
        [coverArt setImage:tempCoverArt];
        lessonTitle.text = currentSelection.title;
        lessonSubtitle.text = currentSelection.subtitle;
        timingLabel.text = currentSelection.timing;
        keySignatureLabel.text = currentSelection.keySignature;
        [difficultyImage setImage:tempDifficulty];
        descriptionTextView.text = currentSelection.lessonDescription;
    }

}

//END TABLE METHODS

- (void)viewDidLoad
{    
    [super viewDidLoad];

    if (managedObjectContext == nil) 
    { 
        managedObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext]; 
    }

    // Song library

    Lesson *Lesson0 = [[Lesson alloc] init];
    Lesson0 = [NSEntityDescription insertNewObjectForEntityForName:@"Lesson" inManagedObjectContext:managedObjectContext];
    Lesson0.productID = 0;
    //Lesson0.purchaseStatus = 1;
    Lesson0.title = @"Happy Birthday to You";
    Lesson0.subtitle = @"Patty & Mildred Hill";
    Lesson0.titleAndSubtitle = @"Happy Birthday to You - Patty & Mildred Hill";
    Lesson0.coverArtFilename = @"beethoven.png";
    Lesson0.timing = @"3/4";
    Lesson0.keySignature = @"G";
    Lesson0.difficultyImageFilename = @"easy.png";
    Lesson0.lessonDescription = @"Originally, this song piece was called 'Good Morning to All' and was sung to and by children in school.";
    Lesson0.sheetFilename = @"1_score";
    Lesson0.midiFilename = @"happyBirthdayToYou";
    Lesson0.materialsFilename = @"1_score";
    Lesson0.roll = @"happyBirthdayToYou";
    //Lesson0.startingIndicatorPosition = 175;
    Lesson0.rollPositionArray = [NSArray arrayWithObjects:   /* 0 */ [NSNumber numberWithInteger:0],
                                 /* 1 */ [NSNumber numberWithInteger:0],    
                                 /* 2 */ [NSNumber numberWithInteger:0],
                                 /* 3 */ [NSNumber numberWithInteger:-65],
                                 /* 4 */ [NSNumber numberWithInteger:-100],
                                 /* 5 */ [NSNumber numberWithInteger:-135],
                                 /* 6 */ [NSNumber numberWithInteger:-185],
                                 /* 7 */ [NSNumber numberWithInteger:-185],
                                 /* 8 */ [NSNumber numberWithInteger:-241],
                                 /* 9 */ [NSNumber numberWithInteger:-306],
                                 /* 10 */ [NSNumber numberWithInteger:-341],
                                 /* 11 */ [NSNumber numberWithInteger:-376],
                                 /* 12 */ [NSNumber numberWithInteger:-426],
                                 /* 13 */ [NSNumber numberWithInteger:-426],
                                 /* 14 */ [NSNumber numberWithInteger:-483],
                                 /* 15 */ [NSNumber numberWithInteger:-548],
                                 /* 16 */ [NSNumber numberWithInteger:-582],
                                 /* 17 */ [NSNumber numberWithInteger:-617],
                                 /* 18 */ [NSNumber numberWithInteger:-666],
                                 /* 19 */ [NSNumber numberWithInteger:-701],
                                 /* 20 */ [NSNumber numberWithInteger:-737],
                                 /* 21 */ [NSNumber numberWithInteger:-799],
                                 /* 22 */ [NSNumber numberWithInteger:-834],
                                 /* 23 */ [NSNumber numberWithInteger:-868],
                                 /* 24 */ [NSNumber numberWithInteger:-918],
                                 nil];

    // Load in the CoreData library of Lessons

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription 
                                   entityForName:@"Lesson" inManagedObjectContext:managedObjectContext];
    [fetchRequest setEntity:entity];
    NSError *error;
    NSArray *tempArray = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
    lessonLibrary = [[NSMutableArray alloc] initWithArray:tempArray];

    NSSortDescriptor *desc = [[NSSortDescriptor alloc] initWithKey:@"subtitle" ascending:YES];
    [lessonLibrary sortUsingDescriptors:[NSArray arrayWithObjects:desc, nil]];

    // Load background images.
    UIImage *detailsDivider = [UIImage imageNamed:@"detailsDividerImage.png"];
    [dividerImage setImage:detailsDivider];

    UIImage *detailsBackground = [UIImage imageNamed:@"detailsBackgroundImage.png"];
    [detailBackgroundImage setImage:detailsBackground];

    UIImage *detailsPanel = [UIImage imageNamed:@"detailsDisplayImage.png"];
    [detailsImage setImage:detailsPanel];

    // Load default cover art.
    UIImage *defaultCoverArt = [UIImage imageNamed:@"coverArtDefault.png"];
    [coverArt setImage:defaultCoverArt];


    if (![managedObjectContext save:&error]) {
        NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
    }

    for (Lesson *lesson in lessonLibrary) {
        [purchasedLessons addObject:lesson];
    }
//    purchasedLessons = [[NSMutableArray alloc] initWithObjects:Lesson0, nil];

}

- (void)viewDidUnload
{
    [self setLessonTitle:nil];
    [self setLessonSubtitle:nil];
    [self setCoverArt:nil];
    [self setTimingLabel:nil];
    [self setKeySignatureLabel:nil];
    [self setDifficultyImage:nil];
    [self setDescriptionTextView:nil];
    [self setDividerImage:nil];
    [self setDetailBackgroundImage:nil];
    [self setDetailsImage:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    // Segue to the materials screen.

    if ([segue.identifier isEqualToString:@"materials"]) {
        PDFViewController *pdfViewController = [segue destinationViewController];

        NSIndexPath *path = [self.tableView indexPathForSelectedRow];
        int row = [path row];
        Lesson *selected = [purchasedLessons objectAtIndex:row];
        pdfViewController.selectedLesson = selected;

        pdfViewController.fileToView = @"materials";

    }

    // Segue to the sheet screen.

    else if ([segue.identifier isEqualToString:@"sheet"]) {
        PDFViewController *pdfViewController = [segue destinationViewController];

        NSIndexPath *path = [self.tableView indexPathForSelectedRow];
        int row = [path row];
        Lesson *selected = [purchasedLessons objectAtIndex:row];

        pdfViewController.selectedLesson = selected;

        pdfViewController.fileToView = @"sheet";
    }

    // Segue to the practice screen.

    else if ([segue.identifier isEqualToString:@"practice"]) {
        PracticeViewController *practiceViewController = [segue destinationViewController];

        NSIndexPath *path = [self.tableView indexPathForSelectedRow];
        int row = [path row];
        Lesson *selected = [purchasedLessons objectAtIndex:row];
        practiceViewController.selectedLesson = selected;
    }
}

@end

Lesson.h

#import <Foundation/Foundation.h>

@interface Lesson : NSObject

@property int purchaseStatus;
@property int productID;
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSString *subtitle;
@property (nonatomic, strong) NSString *titleAndSubtitle;
@property (nonatomic, strong) NSString *coverArtFilename;
@property (nonatomic, strong) NSString *timing;
@property (nonatomic, strong) NSString *keySignature;
@property (nonatomic, strong) NSString *difficultyImageFilename;
@property (nonatomic, strong) NSString *lessonDescription;
@property (nonatomic, strong) NSString *materialsFilename;
@property (nonatomic, strong) NSString *sheetFilename; // PDF
@property (nonatomic, strong) NSString *midiFilename;
@property (nonatomic, strong) NSString *roll;
@property NSArray *rollPositionArray;
@property int startingIndicatorPosition;

@end

Lesson.m

#import "Lesson.h"

@implementation Lesson
@synthesize productID, coverArtFilename, title, subtitle, titleAndSubtitle, timing, keySignature, difficultyImageFilename, lessonDescription, materialsFilename, sheetFilename, midiFilename, purchaseStatus, roll, rollPositionArray, startingIndicatorPosition;

@end

1 个答案:

答案 0 :(得分:0)

我不确定发生了什么,但我重新开始并在第二次开始工作:)它可能与我的AppDelegate寻找模型的地方有关。

相关问题