Ios +;entityForName:nil不是搜索实体名称的合法NSManagedObjectContext参数';印度系列';

Ios +;entityForName:nil不是搜索实体名称的合法NSManagedObjectContext参数';印度系列';,ios,Ios,当我试图将数据从核心数据加载到表视图控制器时出错。我已经根据论坛上的讨论更正了代码,但仍然得到了一个错误 SearchViewController @interface SearchViewController () - (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath; @end @implementation SearchViewController @synthesize m

当我试图将数据从核心数据加载到表视图控制器时出错。我已经根据论坛上的讨论更正了代码,但仍然得到了一个错误

SearchViewController

@interface SearchViewController ()

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath;
@end

@implementation SearchViewController
@synthesize managedObjectContext;
@synthesize fetchedResultsController = _fetchedResultsController;
@synthesize searchBar,tView;
@synthesize noResultsLabel;

 -(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

 -(void)viewDidLoad
{
    [super viewDidLoad];
    self.searchBar.delegate = self;
    self.tView.delegate = self;
    self.tView.dataSource = self;

    noResultsLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 90, 200, 30)];
    [self.view addSubview:noResultsLabel];
    noResultsLabel.text = @"No Results";
    [noResultsLabel setHidden:YES];

    // Do any additional setup after loading the view.
}

 -(void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.searchBar becomeFirstResponder];

}

#pragma mark - Search bar delegate

 -(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar 
{

    NSError *error;

    if (![[self fetchedResultsController] performFetch:&error]) 
{

        NSLog(@"Error in search %@, %@", error, [error userInfo]);

    } else 
{

        [self.tView reloadData];
        [self.searchBar resignFirstResponder];

        [noResultsLabel setHidden:_fetchedResultsController.fetchedObjects.count > 0];

    }
}

#pragma mark - Table view data source

 -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

 -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    id  sectionInfo =
    [[_fetchedResultsController sections] objectAtIndex:section];
    return [sectionInfo numberOfObjects];

}

 -(void)configureCell:(TableCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    IndianGroceries *info = [_fetchedResultsController objectAtIndexPath:indexPath];
    cell.lblCountry.text = info.country;
    cell.lblCityName.text = info.cityName;
    cell.lblEmailId.text = info.emailId;
    cell.lblFirstName.text = info.firstName;
    cell.lblLastName.text = info.lastName;
    cell.lblPhoneNumber.text = info.phoneNumber;
    cell.lblStreetName.text = info.streetName1;
    cell.lblStreetName2.text = info.streetName2;
    cell.lblZipCode.text = info.zipCode;
}

  -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    TableCell *cell = (TableCell *)[self.tView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell=[[TableCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    [self configureCell:cell atIndexPath:indexPath];

    return cell;
}


#pragma mark - fetchedResultsController

// Change this value to experiment with different predicates
#define SEARCH_TYPE 0


 -(NSFetchedResultsController *)fetchedResultsController
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription
                insertNewObjectForEntityForName:@"IndianGroceries" inManagedObjectContext:[self managedObjectContext]];
    [fetchRequest setEntity:entity];

    NSSortDescriptor *sort = [[NSSortDescriptor alloc]
                              initWithKey:@"country" ascending:NO];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
    [fetchRequest setFetchBatchSize:20];

    NSArray *queryArray;

    if ([self.searchBar.text rangeOfString:@":"].location != NSNotFound)
    {
        queryArray = [self.searchBar.text componentsSeparatedByString:@":"];
    }

    NSLog(@"search is %@", self.searchBar.text);

    NSPredicate *pred;

    switch (SEARCH_TYPE) {

        case 0: // name contains, case sensitive
            pred = [NSPredicate predicateWithFormat:@"name CONTAINS %@", self.searchBar.text];
            break;
        default:
            break;
    }

    [fetchRequest setPredicate:pred];

    NSFetchedResultsController *theFetchedResultsController =
    [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                        managedObjectContext:[self managedObjectContext]sectionNameKeyPath:nil
                                                   cacheName:nil]; // better to not use cache
    self.fetchedResultsController = theFetchedResultsController;
    _fetchedResultsController.delegate = self;

    return _fetchedResultsController;

}
@interface DataViewController ()
@property(strong,nonatomic) NSArray *SearchResultContries;
//- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath;

@end

@implementation DataViewController
@synthesize contacts;
@synthesize managedObjectContext;
@synthesize fetchedResultsController = _fetchedResultsController;

-(NSManagedObjectContext *)managedObjectContext
{
    NSManagedObjectContext *context = nil;
    id delegate = [[UIApplication sharedApplication]delegate];

    if ([delegate performSelector:@selector(managedObjectContext)])
    {
        context = [delegate managedObjectContext];
    }
    return context;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:NO animated:YES];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(showSearch)];
    // Do any additional setup after loading the view.
}

-(void)viewDidAppear:(BOOL)animated{

    //here we get the car from the president data store (or) the database
    NSManagedObjectContext *moc = [self managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]initWithEntityName:@"IndianGroceries"];
    contacts = [[moc executeFetchRequest:fetchRequest error:nil]mutableCopy];
    [self.tableView reloadData];

}

-(void)viewWillAppear:(BOOL)animated
{
    [self.tableView reloadData];
}

- (void) showSearch {

    SearchViewController *searchViewController = [[SearchViewController alloc] init];
    searchViewController.managedObjectContext = self.managedObjectContext;
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
    searchViewController = [storyboard instantiateViewControllerWithIdentifier:@"searchView"];
    [self.navigationController pushViewController:searchViewController animated:YES];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return contacts.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CellID";
    TableCell *cell = (TableCell *)[self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
      cell=[[TableCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    NSManagedObject *con = [contacts objectAtIndex:indexPath.row];
    [cell.lblEmailId setText:[NSString stringWithFormat:@"%@",[con valueForKey:@"emailId"]]];
    [cell.lblFirstName setText:[NSString stringWithFormat:@"%@",[con valueForKey:@"firstName"]]];
    [cell.lblLastName setText:[NSString stringWithFormat:@"%@",[con valueForKey:@"lastName"]]];
    [cell.lblStreetName setText:[NSString stringWithFormat:@"%@",[con valueForKey:@"streetName1"]]];
    [cell.lblStreetName2 setText:[NSString stringWithFormat:@"%@",[con valueForKey:@"streetName2"]]];
    [cell.lblCityName setText:[NSString stringWithFormat:@"%@",[con valueForKey:@"cityName"]]];
    [cell.lblZipCode setText:[NSString stringWithFormat:@"%@",[con valueForKey:@"zipCode"]]];
    [cell.lblPhoneNumber setText:[NSString stringWithFormat:@"%@",[con valueForKey:@"phoneNumber"]]];
    [cell.lblCountry setText:[NSString stringWithFormat:@"%@",[con valueForKey:@"country"]]];

    return cell;
}
DataViewController

@interface SearchViewController ()

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath;
@end

@implementation SearchViewController
@synthesize managedObjectContext;
@synthesize fetchedResultsController = _fetchedResultsController;
@synthesize searchBar,tView;
@synthesize noResultsLabel;

 -(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

 -(void)viewDidLoad
{
    [super viewDidLoad];
    self.searchBar.delegate = self;
    self.tView.delegate = self;
    self.tView.dataSource = self;

    noResultsLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 90, 200, 30)];
    [self.view addSubview:noResultsLabel];
    noResultsLabel.text = @"No Results";
    [noResultsLabel setHidden:YES];

    // Do any additional setup after loading the view.
}

 -(void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.searchBar becomeFirstResponder];

}

#pragma mark - Search bar delegate

 -(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar 
{

    NSError *error;

    if (![[self fetchedResultsController] performFetch:&error]) 
{

        NSLog(@"Error in search %@, %@", error, [error userInfo]);

    } else 
{

        [self.tView reloadData];
        [self.searchBar resignFirstResponder];

        [noResultsLabel setHidden:_fetchedResultsController.fetchedObjects.count > 0];

    }
}

#pragma mark - Table view data source

 -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

 -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    id  sectionInfo =
    [[_fetchedResultsController sections] objectAtIndex:section];
    return [sectionInfo numberOfObjects];

}

 -(void)configureCell:(TableCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    IndianGroceries *info = [_fetchedResultsController objectAtIndexPath:indexPath];
    cell.lblCountry.text = info.country;
    cell.lblCityName.text = info.cityName;
    cell.lblEmailId.text = info.emailId;
    cell.lblFirstName.text = info.firstName;
    cell.lblLastName.text = info.lastName;
    cell.lblPhoneNumber.text = info.phoneNumber;
    cell.lblStreetName.text = info.streetName1;
    cell.lblStreetName2.text = info.streetName2;
    cell.lblZipCode.text = info.zipCode;
}

  -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    TableCell *cell = (TableCell *)[self.tView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell=[[TableCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    [self configureCell:cell atIndexPath:indexPath];

    return cell;
}


#pragma mark - fetchedResultsController

// Change this value to experiment with different predicates
#define SEARCH_TYPE 0


 -(NSFetchedResultsController *)fetchedResultsController
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription
                insertNewObjectForEntityForName:@"IndianGroceries" inManagedObjectContext:[self managedObjectContext]];
    [fetchRequest setEntity:entity];

    NSSortDescriptor *sort = [[NSSortDescriptor alloc]
                              initWithKey:@"country" ascending:NO];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
    [fetchRequest setFetchBatchSize:20];

    NSArray *queryArray;

    if ([self.searchBar.text rangeOfString:@":"].location != NSNotFound)
    {
        queryArray = [self.searchBar.text componentsSeparatedByString:@":"];
    }

    NSLog(@"search is %@", self.searchBar.text);

    NSPredicate *pred;

    switch (SEARCH_TYPE) {

        case 0: // name contains, case sensitive
            pred = [NSPredicate predicateWithFormat:@"name CONTAINS %@", self.searchBar.text];
            break;
        default:
            break;
    }

    [fetchRequest setPredicate:pred];

    NSFetchedResultsController *theFetchedResultsController =
    [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                        managedObjectContext:[self managedObjectContext]sectionNameKeyPath:nil
                                                   cacheName:nil]; // better to not use cache
    self.fetchedResultsController = theFetchedResultsController;
    _fetchedResultsController.delegate = self;

    return _fetchedResultsController;

}
@interface DataViewController ()
@property(strong,nonatomic) NSArray *SearchResultContries;
//- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath;

@end

@implementation DataViewController
@synthesize contacts;
@synthesize managedObjectContext;
@synthesize fetchedResultsController = _fetchedResultsController;

-(NSManagedObjectContext *)managedObjectContext
{
    NSManagedObjectContext *context = nil;
    id delegate = [[UIApplication sharedApplication]delegate];

    if ([delegate performSelector:@selector(managedObjectContext)])
    {
        context = [delegate managedObjectContext];
    }
    return context;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:NO animated:YES];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(showSearch)];
    // Do any additional setup after loading the view.
}

-(void)viewDidAppear:(BOOL)animated{

    //here we get the car from the president data store (or) the database
    NSManagedObjectContext *moc = [self managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]initWithEntityName:@"IndianGroceries"];
    contacts = [[moc executeFetchRequest:fetchRequest error:nil]mutableCopy];
    [self.tableView reloadData];

}

-(void)viewWillAppear:(BOOL)animated
{
    [self.tableView reloadData];
}

- (void) showSearch {

    SearchViewController *searchViewController = [[SearchViewController alloc] init];
    searchViewController.managedObjectContext = self.managedObjectContext;
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
    searchViewController = [storyboard instantiateViewControllerWithIdentifier:@"searchView"];
    [self.navigationController pushViewController:searchViewController animated:YES];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return contacts.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CellID";
    TableCell *cell = (TableCell *)[self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
      cell=[[TableCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    NSManagedObject *con = [contacts objectAtIndex:indexPath.row];
    [cell.lblEmailId setText:[NSString stringWithFormat:@"%@",[con valueForKey:@"emailId"]]];
    [cell.lblFirstName setText:[NSString stringWithFormat:@"%@",[con valueForKey:@"firstName"]]];
    [cell.lblLastName setText:[NSString stringWithFormat:@"%@",[con valueForKey:@"lastName"]]];
    [cell.lblStreetName setText:[NSString stringWithFormat:@"%@",[con valueForKey:@"streetName1"]]];
    [cell.lblStreetName2 setText:[NSString stringWithFormat:@"%@",[con valueForKey:@"streetName2"]]];
    [cell.lblCityName setText:[NSString stringWithFormat:@"%@",[con valueForKey:@"cityName"]]];
    [cell.lblZipCode setText:[NSString stringWithFormat:@"%@",[con valueForKey:@"zipCode"]]];
    [cell.lblPhoneNumber setText:[NSString stringWithFormat:@"%@",[con valueForKey:@"phoneNumber"]]];
    [cell.lblCountry setText:[NSString stringWithFormat:@"%@",[con valueForKey:@"country"]]];

    return cell;
}

您传递给托管对象上下文中的entityForName:inManagedObjectContext:的
NSManagedObjectContext
为零。该方法需要有效的NSManagedObjectContext实例

看看这个答案:

请发布一些代码,错误发生在哪一行?是否添加了异常断点?然后,您将能够看到什么是零以及为什么是零。是的,错误出现在下面代码的最后一行:-(NSFetchedResultsController*)fetchedResultsController{NSFetchRequest*fetchRequest=[[NSFetchRequest alloc]init];NSEntityDescription*entity=[NSEntityDescription insertNewObjectForEntityForName:@“IndiangRoSeries”inManagedObjectContext:[self-managedObjectContext]];[fetchRequest setEntity:entity];这不是答案。如果问题是重复的,则投票将其作为重复关闭。这是答案。他的问题是“我为什么会出现此错误”。这是因为他的上下文为零。他在问题中没有提供足够的信息来说明如何准确地解决它,也没有提供足够的信息来确定它是否是重复的。不管怎样,他的问题是他在零上下文中传递。您的回答是“查看另一个堆栈溢出问题的答案”。我不想知道“为什么会出现此错误”我只想解决此错误。请帮助我解决。不。我的回答是“该方法需要有效的NSManagedObjectContext实例”。我向他指出了另一个问题,因为他没有提供任何信息说明其上下文为何为零,这可能会促使他朝正确的方向前进。