11

I've tried the proposed solutions for similar questions on SO but with no luck. The fetch request can't locate the entity name 'GarmentType'.

Here is my data model: enter image description here

The error is thrown at the executeFetchRequest in this helper category:

//
//  GarmentType+Create.m
//  Dressy
//
//  Created by Michael Mangold on 9/4/13.
//  Copyright (c) 2013 Michael Mangold. All rights reserved.
//

#import "GarmentType+Create.h"

@implementation GarmentType (Create)

// Creates or fetches a Core Data GarmentType entity.
+ (GarmentType *)garmentTypeWithName:(NSString *)name inManagedObjectContext:(NSManagedObjectContext *)context
{
    NSLog(@"name:%@ context:%@",name,context);
    GarmentType *garmentType = nil;

    // Build fetch request.
    NSFetchRequest *request          = [NSFetchRequest fetchRequestWithEntityName:@"GarmentType"];
    request.sortDescriptors          = @[[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]];
    request.predicate                = [NSPredicate predicateWithFormat:@"name = %@",name];

    // Execute fetch requesst.
    NSError *error  = nil;
    NSArray *matches = [context executeFetchRequest:request error:&error]; // This is where it dies.

    if (!matches || [matches count] > 1) {
        NSLog(@"Error creating GarmentType.");
    } else if ([matches count] == 0) {
        garmentType          = [NSEntityDescription insertNewObjectForEntityForName:@"GarmentType" inManagedObjectContext:context];
        garmentType.name     = name;
    } else {
        garmentType = [matches lastObject];
    }

    return garmentType;
}

@end

The name logs the correct name and the context is non nil.

The helper is called from a UITableViewController IBAction when the 'done' button is pressed:

- (IBAction)handleDoneButton:(UIBarButtonItem *)sender
{
    // Add garment type to core data.
    [DressyHelper openDocumentUsingBlock:^(UIManagedDocument *document){
        GarmentType *newGarment = [GarmentType garmentTypeWithName:self.garmentTypeNameTextField.text inManagedObjectContext:document.managedObjectContext];
        NSLog(@"newGarment.name:%@",newGarment.name);
    }];
    [self dismissViewControllerAnimated:YES completion:nil];
}

newGarment.name logs fine.

Here is the .h for GarmentType:

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>

@class Garment;

@interface GarmentType : NSManagedObject

@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSSet *garments;
@end

@interface GarmentType (CoreDataGeneratedAccessors)

- (void)addGarmentsObject:(Garment *)value;
- (void)removeGarmentsObject:(Garment *)value;
- (void)addGarments:(NSSet *)values;
- (void)removeGarments:(NSSet *)values;

@end

Apologies for the code dump but I've been struggling with this for a while. Changing the entity name results in the same error, just with the new name as the entity not found.

Inspector for GarmentType: enter image description here

And the exception:

2013-12-10 13:51:50.320 Dressy[4336:70b] name:asdf context:<NSManagedObjectContext: 0x8ad86f0>
2013-12-10 13:51:50.323 Dressy[4336:70b] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'NSFetchRequest could not locate an NSEntityDescription for entity name 'GarmentType''
*** First throw call stack:
(
    0   CoreFoundation                      0x017465e4 __exceptionPreprocess + 180
    1   libobjc.A.dylib                     0x014c98b6 objc_exception_throw + 44
    2   CoreData                            0x019b4b6e -[NSFetchRequest(_NSInternalMethods) _resolveEntityWithContext:] + 510
    3   CoreData                            0x019b34d6 -[NSManagedObjectContext executeFetchRequest:error:] + 70
    4   Dressy                              0x000051de +[GarmentType(Create) garmentTypeWithName:inManagedObjectContext:] + 510
    5   Dressy                              0x00002170 __54-[GarmentTypeAddTableViewController handleDoneButton:]_block_invoke + 208
    6   Dressy                              0x00006d51 __39+[DressyHelper openDocumentUsingBlock:]_block_invoke21 + 97
    7   UIKit                               0x00781f7b __59-[UIDocument saveToURL:forSaveOperation:completionHandler:]_block_invoke570 + 54
    8   libdispatch.dylib                   0x01e43440 _dispatch_barrier_sync_f_slow_invoke + 71
    9   libdispatch.dylib                   0x01e544b0 _dispatch_client_callout + 14
    10  libdispatch.dylib                   0x01e4275e _dispatch_main_queue_callback_4CF + 340
    11  CoreFoundation                      0x017aba5e __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 14
    12  CoreFoundation                      0x016ec6bb __CFRunLoopRun + 1963
    13  CoreFoundation                      0x016ebac3 CFRunLoopRunSpecific + 467
    14  CoreFoundation                      0x016eb8db CFRunLoopRunInMode + 123
    15  GraphicsServices                    0x03a4d9e2 GSEventRunModal + 192
    16  GraphicsServices                    0x03a4d809 GSEventRun + 104
    17  UIKit                               0x00237d3b UIApplicationMain + 1225
    18  Dressy                              0x0000585d main + 141
    19  libdyld.dylib                       0x020e670d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

TIA

6
  • The only question I would ask is whether or not an Entity of GarmentType has been created in this instance of your NSManagedObjectContext. You may want to enable lightweight migration or to be completely sure, delete the app from the simulator and run the app again. If it still dies, something weird is happening.
    – atreat
    Dec 10, 2013 at 17:27
  • Thanks for responding. The database is completely empty at this point and this would be the first GarmentType being created. Dec 10, 2013 at 17:30
  • Do you have multiple Model Versions by any chance?
    – Snowman
    Dec 10, 2013 at 20:39
  • I don't think so, how would I check to be certain? Thanks for responding. Dec 10, 2013 at 20:46
  • Are you able to perform a fetch request for GarmentType by using the main MOC of your app? I'm wondering whether this DressyHelper or UIManagedDocument is the problem.
    – ChrisH
    Dec 11, 2013 at 0:26

3 Answers 3

21

I finally found the problem. The .xcdatamodel wasn't included in the target membership. Selecting the xcdatamodel in the navigator pane on the left in Xcode, then selecting the first tab (File inspector) in the Utilities pane on the right, then selecting the data model in the Target Membership section fixes the problem. Thank you so much to everyone who responded.

enter image description here

2
  • 3
    I have that selected and yet I have this problem. it must be something else you did that solved it.
    – AceN
    Jan 16, 2015 at 7:44
  • Clear and straight answer, really helpful
    – Aamir
    Aug 23, 2017 at 7:24
4

The Entity diagram with Entity names is only half of the puzzle. For each entity, what have you defined the class names as? That is what fetchRequestWithEntityName: will go against.

EDIT:

Since the class name is resolved, what is the exception you are getting? After you continue, does CoreData explain what the problem is that it had? Does the application actually crash (I ask that because if you have a breakpoint set for exceptions, Core Data will often throw internal exceptions that don't matter or cause the application to crash)?

EDIT2:

The crash doesn't say much beyond us knowing you have a valid context. The next step would be, to list all of the entities at a breakpoint set just before the fetch request, using code like:

NSManagedObjectModel *managedObjectModel = [[context persistentStoreCoordinator] managedObjectModel];
NSDictionary *entities = [managedObjectModel entitiesByName];
NSArray *entityNames = [entities allKeys];
NSLog(@"All loaded entities are: %@", entityNames);
16
  • Thanks for responding. Here is the .h for GarmentType: Dec 10, 2013 at 17:37
  • Couldn't post the .h, but it is named GarmentType. I added the .h code in the original post. Thanks again for responding. Dec 10, 2013 at 17:38
  • But is the class name set to GarmentType in the data model itself? Dec 10, 2013 at 17:44
  • Yes, you can see in the image of the data model above that the class name is GarmentType, unless there's a different place to specify I'm not aware of. Dec 10, 2013 at 18:04
  • 1
    Somehow you must have skipped a step loading the data model into the model.. normally it loads whatever models it can find in the bundle. That is your problem though, there's no way a fetch or anything is going to work until it knows about entities. If I were you I'd ask a new question on StackOverflow framed around "why are my entities not loaded in my managed object model when using a UIManagedDocument" Dec 11, 2013 at 22:29
2

I got this after creating a new model version with a new entity, but forgetting to update data file URL:

NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Data2.0" <==== Here
                                          withExtension:@"mom"
                                           subdirectory:@"Data.momd"];

_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
1
  • Thank you. This was exactly my issue. I had 7 versions of the schema and had not updated the 'URLForResource' to reflect the currently selected data model version. I would think selecting the current model under 'Model Version' in the right properties panel under 'Core Data Model' would take care of this for you, but apparently this is not true. Or maybe it is just no longer true (ie Defect in XCode) Apr 13, 2019 at 22:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.