Advertise Mobile SDKs Books Events Forum News Social Networking Support Us
Follow @iphonedevsdk on Twitter

Interface 2, Advanced iOS
Mockup & Code Gen
($9.99)

Make your own iPhone apps
and run them live!
(free)

Pic Frame Dynamo: Photo Editing
($0.99)

Abiliator
($1.99)

Want your application or service advertised on iPhone Dev SDK?

Go Back   iPhone Dev SDK Forum > iPhone SDK Development Forums > iPhone SDK Development

Reply
 
LinkBack Thread Tools Display Modes
Old 03-30-2011, 10:37 AM   #1 (permalink)
Registered Member
 
Join Date: Jan 2010
Location: MA
Posts: 126
nd049 is on a distinguished road
Default Core Data Question

Hi Everyone,

I am working on my first Core Data app, and I am following along with the iPhoneCoreDataRecipes example. I am pretty much just looking for the functionality of being able to add/remove items in a TableView - like in the example. However I have come across a problem that I can't seem to find an answer too online.

When I am setting up the NSFetchedResultsController, my app is crashing with the error:

Quote:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '+entityForName: could not locate an NSManagedObjectModel for entity name 'Gig''
I do have a NSManagedObject Class called Gig and my data model appears to be set up correctly. The code that I have is the following:

Header File
Code:
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
#import "GigAddViewController.h"

@class Gig;
@class GigTableViewCell;

@interface GigsListTableViewController : UIViewController <UITableViewDelegate, NSFetchedResultsControllerDelegate, GigAddDelegate> {
    IBOutlet UITableView *gigsTable;
    
@private
    NSFetchedResultsController *fetchedResultsController;
    NSManagedObjectContext *managedObjectContext;
}

@property (nonatomic, retain) UITableView *gigsTable;
@property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController;
@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;

- (void)showGig:(Gig *)gig animated:(BOOL)animated;
- (void)configureCell:(GigTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath;

@end
Implementation
Code:
- (void)viewDidLoad {
    
    self.navigationItem.leftBarButtonItem = self.editButtonItem;
    
    UIBarButtonItem *addButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(add:)];
    self.navigationItem.rightBarButtonItem = addButtonItem;
    [addButtonItem release];

    // Set the table view's row height
    self.gigsTable.rowHeight = 65.0;
    
    NSError *error = nil;
	if (![[self fetchedResultsController] performFetch:&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. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
		 */
		NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
		abort();
	}
    
    [super viewDidLoad];
}
This is the method it is crashing in after ViewDidLoad is called.
Code:
- (NSFetchedResultsController *)fetchedResultsController {
    // Set up the fetched results controller if needed.
    if (fetchedResultsController == nil) {
        // Create the fetch request for the entity.
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        // Edit the entity name as appropriate.
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Gig" inManagedObjectContext:managedObjectContext];
        [fetchRequest setEntity:entity];
        
        // Edit the sort key as appropriate.
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
        NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
        
        [fetchRequest setSortDescriptors:sortDescriptors];
        
        // Edit the section name key path and cache name if appropriate.
        // nil for section name key path means "no sections".
        NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"];
        aFetchedResultsController.delegate = self;
        self.fetchedResultsController = aFetchedResultsController;
        
        [aFetchedResultsController release];
        [fetchRequest release];
        [sortDescriptor release];
        [sortDescriptors release];
    }
	
	return fetchedResultsController;
}

Any help would be greatly appreciated!
nd049 is offline   Reply With Quote
Old 03-30-2011, 10:49 AM   #2 (permalink)
Registered Member
 
Join Date: Apr 2010
Posts: 46
kasparp is on a distinguished road
Default

Did you run your app then make changes to your datamodel and then run again ?
That will make your database version older than your datamodel, you need to delete the sqlite db in app directory, for my app the path is:
/Users/kaspar/Library/Application Support/iPhone Simulator/4.3/Applications/E0C9D62E-7EF6-4DD8-ABF8-0B0E8E535C18/Documents/Databasename.sqlite

Delete the file and try running it again it should work (i think )

Edit: In production you should of cause check for old version and make mapping model, since this is just development deleting the database is easier :=)
__________________
Cheers

Last edited by kasparp; 03-30-2011 at 10:59 AM.
kasparp is offline   Reply With Quote
Old 03-30-2011, 12:34 PM   #3 (permalink)
Registered Member
 
Join Date: Jan 2010
Location: MA
Posts: 126
nd049 is on a distinguished road
Default

Quote:
Originally Posted by kasparp View Post
Did you run your app then make changes to your datamodel and then run again ?
That will make your database version older than your datamodel, you need to delete the sqlite db in app directory, for my app the path is:
/Users/kaspar/Library/Application Support/iPhone Simulator/4.3/Applications/E0C9D62E-7EF6-4DD8-ABF8-0B0E8E535C18/Documents/Databasename.sqlite

Delete the file and try running it again it should work (i think )

Edit: In production you should of cause check for old version and make mapping model, since this is just development deleting the database is easier :=)
I had modified the data model... So i did delete the sqlite database, but when I ran it again and it still crashed.

Any other ideas?
nd049 is offline   Reply With Quote
Old 03-30-2011, 03:02 PM   #4 (permalink)
Registered Member
 
Join Date: Apr 2010
Posts: 46
kasparp is on a distinguished road
Default

Quote:
Originally Posted by nd049 View Post
I had modified the data model... So i did delete the sqlite database, but when I ran it again and it still crashed.

Any other ideas?
Hmm maybe managedObjectContext is not initialized correct? thats the only other explanation I can come up with
__________________
Cheers
kasparp is offline   Reply With Quote
Old 03-30-2011, 07:03 PM   #5 (permalink)
Registered Member
 
Join Date: Jan 2010
Location: MA
Posts: 126
nd049 is on a distinguished road
Default

Quote:
Originally Posted by kasparp View Post
Hmm maybe managedObjectContext is not initialized correct? thats the only other explanation I can come up with
I dont think that it is initialized wrong... but maybe. In the app delegate I have:

Code:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    // Override point for customization after application launch.
    // Add the tab bar controller's current view as a subview of the window
    gigsListController.managedObjectContext = self.managedObjectContext;
    
    self.window.rootViewController = self.tabBarController;
    [self.window makeKeyAndVisible];
    return YES;
}
To set the main view (gigListController) and then to initialize it I used:

Code:
/**
 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 new];
        [managedObjectContext setPersistentStoreCoordinator: coordinator];
    }
    return managedObjectContext;
}


/**
 Returns the managed object model for the application.
 If the model doesn't already exist, it is created by merging all of the models found in the application bundle.
 */
- (NSManagedObjectModel *)managedObjectModel {
	
    if (managedObjectModel != nil) {
        return managedObjectModel;
    }
    managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];    
    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;
    }
    
	NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"Gigs.sqlite"];
	/*
	 Set up the store.
	 For the sake of illustration, provide a pre-populated default store.
	 */
	NSFileManager *fileManager = [NSFileManager defaultManager];
	// If the expected store doesn't exist, copy the default store.
	if (![fileManager fileExistsAtPath:storePath]) {
		NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"Gigs" ofType:@"sqlite"];
		if (defaultStorePath) {
			[fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL];
		}
	}
	
	NSURL *storeUrl = [NSURL fileURLWithPath:storePath];
	
	NSError *error;
    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];
    if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) {
		
		NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
		abort();
    }    
    
    return persistentStoreCoordinator;
}
which is almost identical to the code that is in iPhoneCoreDataRecipies. I'm at a loss!
nd049 is offline   Reply With Quote
Old 03-30-2011, 07:10 PM   #6 (permalink)
Registered Member
 
Join Date: Jan 2010
Location: MA
Posts: 126
nd049 is on a distinguished road
Default

Never mind! The variable in my app delegate wasn't being passed into my main view. So I ended up initializing it in the app delegate and then calling:

Code:
ManagerAppDelegate *appDelegate = [[ManagerAppDelegate alloc] init]; 
    self.managedObjectContext = appDelegate.managedObjectContext;
and its working, thanks for all your help kasparp!
nd049 is offline   Reply With Quote
Reply

Bookmarks

Tags
core data, tableview

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



» Advertisements
» Online Users: 366
12 members and 354 guests
condor304, dansparrow, dre, ilmman, LezB44, michelle, Objective Zero, samdanielblr, Sami Gh, shagor012, thephotographer, tinamm64
Most users ever online was 1,387, 04-10-2012 at 04:21 AM.
» Stats
Members: 175,663
Threads: 94,119
Posts: 402,896
Top Poster: BrianSlick (7,990)
Welcome to our newest member, LezB44
Powered by vBadvanced CMPS v3.1.0

All times are GMT -5. The time now is 01:36 AM.
Powered by vBulletin® Version 3.8.0
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.3.0