Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8363153
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T12:06:35+00:00 2026-06-09T12:06:35+00:00

I have an existing project that I am adding the CoreData framework to but

  • 0

I have an existing project that I am adding the CoreData framework to but I’m running into some trouble. I’ve added CoreData to existing projects before but I’m not sure where I’m going wrong in this case.

I have added all of the necessary code to the AppDelegate.h and .m files. I have added the import statement to my .pch. I’ve created my data model file with all of the properties of my Lesson object. I’ve done everything I can think of but when my viewDidLoad method runs through, my managedObjectContext is still nil.

I’ve posted the code for my AppDelegate and my ViewController below. Hopefully someone can offer some advice regarding where I went wrong. Thank you 🙂

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 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T12:06:36+00:00Added an answer on June 9, 2026 at 12:06 pm

    I’m not sure what happened but I started over and got it to work on the second go around 🙂 It may had had something to do with where my AppDelegate was looking for the model.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an existing project that consumes web services. One was added as a
I have an existing project that builds fine using my IDE. I'd like to
I have an existing report (Crystal Report) in my Visual Studio project that is
I have a custom HttpModule rewrite engine in an existing web application project that
I have an existing Java project in Netbeans that uses Swing and I would
I have several somewhat separate programs, that conceptually can fit into a single project.
I've been adding some new css to an existing project (using media=print) in the
I have an existing project, so I need a solid way of cleaning/checking user
I have an existing project written in Ruby on Rails. It is sort of
I have an existing project repo which I use for project A, and has

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.