简体   繁体   中英

Core data error iPhone

My application has multiple view controllers. In my VehicleListController I am saving the data to core data. And in FavouritesController I am fetching the data from core data to display it in table view.

I am getting this error while checking the favouritesController table to view the core data.

'NSInternalInconsistencyException', reason: '+entityForName: could not locate an NSManagedObjectModel for entity name 'Favouritesdata''

Entity Name is Favouritesdata.

In application delegate method didFinishLaunchingWithOptions is as

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *user = [defaults objectForKey:@"Username"];
NSString *passwd = [defaults objectForKey:@"Password"];

if ((user != nil) && (passwd != nil)) {

    NSLog(@"Data found");

    self.progressView = [[Progressbar alloc] initWithNibName:@"Progressbar" bundle:nil];
    self.window.rootViewController = self.progressView;
    [self.window makeKeyAndVisible];

}
else {

    NSLog(@"No data saved");

    self.viewController = [[VektorViewController alloc] initWithNibName:@"VektorViewController" bundle:nil];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
}

return YES;}

In favouritesController.m to fetch the data

-(void)getData {

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Favouritesdata" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setFetchBatchSize:20];
[request setEntity:entity];
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"licensePlate" ascending:YES];
NSArray *newArray = [NSArray arrayWithObject:sort];
[request setSortDescriptors:newArray];
NSError *error;
NSMutableArray *results = [[context executeFetchRequest:request error:&error] mutableCopy];
[self setLicensePlateArray:results];
[self.favouritesTable reloadData];
}

And in cellForRowAtIndexPath in favouritesController

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

static NSString *CellIdentifier = @"Cell";  

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {

    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

    UILongPressGestureRecognizer *pressRecongnizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(tableCellPressed:)];
    pressRecongnizer.minimumPressDuration = 0.5f;
    [cell addGestureRecognizer:pressRecongnizer];
    [pressRecongnizer release];
}

Favouritesdata *favdata = [licensePlateArray objectAtIndex:indexPath.row];

NSLog(@"favdata: %@", favData);

if ([tableView isEqual:self.searchDisplayController.searchResultsTableView]){
    cell.textLabel.text = 
    [self.filteredListItems objectAtIndex:indexPath.row];
}
else{
    cell.textLabel.text = [favdata licenseplate];
   // [self.licensePlateArray objectAtIndex:indexPath.row];
}

return cell;}

Core data accessors in application delegate.m:

- (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;
}
managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];

return managedObjectModel;}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator != nil) {
    return persistentStoreCoordinator;
}
NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory]
                                           stringByAppendingPathComponent: @"LoginTest.sqlite"]];
NSError *error = nil;
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]
                              initWithManagedObjectModel:[self managedObjectModel]];
if(![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
                                             configuration:nil URL:storeUrl options:nil error:&error]) {
    /*Error for store creation should be handled in here*/
}

return persistentStoreCoordinator;}

- (NSString *)applicationDocumentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];}

I have added core data to an existing project. Now I don't know why I am getting this error while I think I have copied the all required methods and framework to my project.

Can anyone tell me please ?

It seems like CoreData has simply not been initialized to have your model loaded before you try to access that entity. Put a breakpoint in both the code that gets out the entity and also the code that loads the CoreData model and see which is called first (or if there are any errors loading your data model).

I think your context is probably nil (I can produce the same error in my application with a nil context). It's in your getData method :

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Favouritesdata" inManagedObjectContext:context];

Can you past the code where you initialize the context ?

The error message is pretty clear : there is no instance of NSManagedObjectModel around.

I used Core Data in only one project and I don't know if this is a universally acclaimed way to do this, but I set up the various Core Data related objects in the application delegate, and then pass the managed object context around to every controller who needs it.

But anyway, Core Data is a bit complicated at first. Try and read some stuff about it.

If it can help you, this is how I did it.

- (NSManagedObjectModel*) managedObjectModel
{
    if(!_managedObjectModel)
    {
        NSString* modelPath = [[NSBundle mainBundle] pathForResource:@"Model" 
                                                              ofType:@"momd"];
        NSURL* modelURL = [NSURL fileURLWithPath:modelPath];
        _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    }

    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator*) persistentStoreCoordinator
{
    if(!_persistentStoreCoordinator)
    {
        NSError* error = nil;
        NSURL* storeURL = [NSURL fileURLWithPath:self.dataStorePath];
        NSDictionary* options = [NSDictionary dictionaryWithObjectsAndKeys:
                                 [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                                 [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

        _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] 
                                       initWithManagedObjectModel:self.managedObjectModel];

        if(![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType 
                                                      configuration:nil 
                                                                URL:storeURL 
                                                            options:options
                                                              error:&error]) 
        {
            #warning handle core data error
            NSLog(@"Error adding persistent store %@, %@", error, error.userInfo);
            abort();
        }
    }

    return _persistentStoreCoordinator;
}

- (NSManagedObjectContext*) managedObjectContext
{
    if(!_managedObjectContext)
    {
        NSPersistentStoreCoordinator* coordinator = self.persistentStoreCoordinator;

        if(coordinator)
        {
            _managedObjectContext = [[NSManagedObjectContext alloc] init];
            [_managedObjectContext setPersistentStoreCoordinator:coordinator];
        }
    }

    return _managedObjectContext;
}

Two things:

  • Make sure you have an Entity in your Core Data model named "Favouritesdata" (very much case sensitive).
  • Not really related to your question, but it's not a good idea to store a password in NSUserDefaults. Username OK, but not a password. This can be cracked by someone with the right knowledge and you don't want to store this kind of stuff on the phone if you can help it.

Refer to this question on stack overflow

Core-Data iPhone: could not locate an NSManagedObjectModel

I have applied the same code in my application as Vivas suggested:

Placing the following code inside of the RootViewController's viewDidLoad eliminates the error:

if (managedObjectContext == nil) { 
    managedObjectContext = [(CoreDataBooksAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext]; 
    NSLog(@"After managedObjectContext: %@",  managedObjectContext);}

Now I am not getting that error :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM