核心数据错误iPhone

问题描述:

我的应用程序有多个视图控制器.在我的VehicleListController中,我将数据保存为核心数据.在FavouritesController中,我正在从核心数据中获取数据以在表格视图中显示.

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.

我在检查favouritesController表以查看核心数据时遇到此错误.

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

实体名称为Favouritesdata.

Entity Name is Favouritesdata.

在应用程序委托方法中,didFinishLaunchingWithOptions为

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;}

在favouritesController.m中获取数据

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];
}

并且在favoritesController中的cellForRowAtIndexPath中

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;}

应用程序委托.m中的核心数据访问器:

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.

有人可以告诉我吗?

错误消息非常清楚:周围没有NSManagedObjectModel实例.

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

我仅在一个项目中使用了Core Data,但我不知道这是否是一种广受赞誉的方式,但是我在应用程序委托中设置了各种与Core Data相关的对象,然后传递了托管对象上下文到需要它的每个控制器周围.

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.

但是无论如何,Core Data起初有点复杂.尝试并阅读一些有关它的内容.

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;
}