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

时间:2014-08-27 09:12:43

标签: ios

当我尝试将数据从Core Data加载到Table View控制器时,出现错误。我根据论坛中的讨论更正了代码,但仍然收到错误。

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;

}

DataViewController

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

1 个答案:

答案 0 :(得分:-1)

您传递给NSManagedObjectContext的{​​{1}}为零。该方法需要有效的NSManagedObjectContext实例。

看到这个答案: '+entityForName: nil is not a legal NSManagedObjectContext parameter - Core Data