entityForName:nil不是合法的NSManagedObjectContext参数,用于搜索实体名称'Concepto'

时间:2015-07-14 21:48:41

标签: ios objective-c

这是发给我的错误

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'Concepto''

这些是我的代码CoreDataStack.h

 #import "NewsManager.h"
    #import "CoreData/CoreData.h"
    #import <sqlite3.h>


    @import Foundation;
    @import CoreData;

    @interface CoreDataStack : NSObject

    //propiedades
    @property(strong, nonatomic)NSManagedObjectContext *managedObjectContext;
    @property(strong, nonatomic)NSManagedObjectModel *managedObjectModel;
    @property(strong, nonatomic)NSPersistentStoreCoordinator *persistentStoreCoordinator;
    @property (strong, nonatomic) UIWindow *window;

    //Metodos
    -(void)saveContext;
    -(NSURL *)applicationDocumentsDirectory;
    @end

这些是我的代码CoreDataStack.m

    #import "CoreDataStack.h"

@implementation CoreDataStack

@synthesize window = _window;
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

#define MODEL_NAME @"Model"

#pragma mark - Core Data stack
-(NSManagedObjectContext *)ManagedObjectContext
{
    if (_managedObjectContext != nil)
    {
        return _managedObjectContext;
    }

    //Pedir una NSPersistentStoreCoordinator()
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil)
    {
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }

    return _managedObjectContext;
}



//Devuelve el coordinador de almacenamiento persistente para la aplicación.
//Si el coordinador no existe, se crea y la tienda de la aplicación añade a la misma.
-(NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil)
    {
        return _persistentStoreCoordinator;
    }
    //NSString *pathString = [NSString stringWithFormat:@"%@Model.sqlite", MODEL_NAME];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Model.splite"];
    NSError *error = nil;

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

    //NSDictionary *options = @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES};




    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:nil])
    {

        NSLog(@"error sin resolver %@, %@", error, [error userInfo]);
        abort();
    }
    return _persistentStoreCoordinator;
}





-(NSManagedObjectModel *)managedObjectModel
{
    if (_managedObjectModel != nil)
    {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Model" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}





- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *manegedObjectContext = self.managedObjectContext;
    if (manegedObjectContext != nil)
    {
        if ([manegedObjectContext hasChanges] && ![manegedObjectContext save:&error])
        {
            NSLog(@"Unresolved error %@, %@",error,[error userInfo]);
            abort();
        }
    }
}

这些是我的代码ModelUtil.h

#import <UIKit/UIKit.h>
#import "IPhoneSigninViewController.h"
#import "BaseSigninViewController.h"
#import "Concepto.h"



@interface ModelUtil : BaseSigninViewController <ADDConceptos>

@property (strong, nonatomic) NSFetchedResultsController *fetchedResultsController;
@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;


@end

这些是我的代码ModelUtil.m

#import "Concepto.h"
#import "ModelUtil.h"

@implementation ModelUtil
@synthesize fetchedResultsController = __fetchedResultsController;
@synthesize managedObjectContext = __managedObjectContext;

-(void)setupFetchedResultsController
{
    // 1 - Decida lo que quiere la Entidad
    NSString *entityName = @"Concepto";
    // Ponga su nombre de la entidad aquí
    NSLog(@"Configuración de un Controlador de resultados recuperados de la Entidad con nombre%@", entityName);

    // 2 - Solicitar que la Entidad
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:entityName];
    // 4 - ordena los datos que se recupera
    request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"dato1, dato2"
                                                                                     ascending:YES
                                                                                      selector:@selector(localizedCaseInsensitiveCompare:)]];
    self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
                                                                        managedObjectContext:self.managedObjectContext
                                                                          sectionNameKeyPath:nil
                                                                                   cacheName:nil];

}

-(void)prepareForSegue:(UIStoryboardPopoverSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"Add Concepto Segue"]) {

        NSLog(@"ddddddd");

        IPhoneSigninViewController *addIPhoneSigninViewController  = segue.destinationViewController;
        addIPhoneSigninViewController.delegate = self;
        addIPhoneSigninViewController.managedObjectContext = self.managedObjectContext;
    }
}

-(void)theSaveButtonOnTheAddRoleTVCWasTapped:(IPhoneSigninViewController *)controller
{
   [controller.navigationController popToRootViewControllerAnimated:YES];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setupFetchedResultsController];
}


@end

这些是我的代码IPhoneSigninViewController.h //

    #import "BaseSigninViewController.h"
    #import <UIKit/UIKit.h>
    #import "Concepto.h"
    @class IPhoneSigninViewController;
    @protocol ADDConceptos <NSObject>
    - (void)theSaveButtonOnTheAddRoleTVCWasTapped:(IPhoneSigninViewController *)controller;
    @end


@interface IPhoneSigninViewController : BaseSigninViewController <UITextFieldDelegate, UIAlertViewDelegate>

@property (nonatomic, weak)id <ADDConceptos> delegate;

- (IBAction)signinButton:(id)sender;
- (IBAction)signinCancel:(id)sender;

@property (weak, nonatomic) IBOutlet UITextField *password;
@property (weak, nonatomic) IBOutlet UITextField *email;
@property (weak, nonatomic) IBOutlet UINavigationBar *navigationBar;
@property (weak, nonatomic) IBOutlet UINavigationItem *NavigationItem;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIView *formView;

@property (weak, nonatomic) IBOutlet UIButton *signupButton;

@property (weak, nonatomic) IBOutlet UIButton *remindButton;

- (void)resignOnTap:(id)iSender;

@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@end

这些是我的代码IPhoneSigninViewController.m

//Guardar el email en el coredata
#pragma mark Guardar El usuario en el core data
-(void)SaveUsername
{
    Concepto *cont = [NSEntityDescription insertNewObjectForEntityForName:@"Concepto" inManagedObjectContext:self.managedObjectContext];
    cont.dato1 = email.text;
    cont.dato2 = password.text;
    [self.managedObjectContext save:nil];
    [self.delegate theSaveButtonOnTheAddRoleTVCWasTapped:self];
    [self SaveUsername];
}






#pragma mark Boton de inicio de secion

-(void)signinButton:(id)sender
{
    NSLog(@"guardar datotes");

     [self SaveUsername];
    [self signInProcess];

}

其中一位已经拥有更多ios经验的人我可以解释如何修复错误......

1 个答案:

答案 0 :(得分:0)

我不确定你用这两行来实现目标 -

self.managedObjectContext = [[[segue destinationViewController]viewControllers] objectAtIndex:0];
[[segue destinationViewController]setManagedObjectContext:self.managedObjectContext]; 

但我相当肯定他们会将当前视图控制器和目标视图控制器的managedObjectContext属性设置为nil或者可能设置为UIViewController的实例也不对。删除这些行。

此外,按照惯例,变量以小写字母开头,因此您应该使用 -

IPhoneSigninViewController *addIPhoneSigninViewController  = segue.destinationViewController;
addIPhoneSigninViewController.delegate = self;
addIPhoneSigninViewController.managedObjectContext = self.managedObjectContext;