2013-08-04 3 views
1

В настоящее время я пытаюсь сделать приложение для iPhone и наткнулся на небольшой удар. Я продолжаю получать ошибку при использовании NSFetchedResultsControllerDelegate и везде, где я использую контроллер NSFetchedResults. Поскольку я внедряю Core Data в свой код, важно, чтобы это работало. Любая обратная связь приветствуется.Основные данные NSFetchedResultsControllerDelegate Issue

Вот код:

ClassTableViewController.h

#import <UIKit/UIKit.h> 
#import "Classes.h" 

//@protocol NewClassViewControllerDelegate; 


@interface NewClassViewController : UIViewController 

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

@property (weak, nonatomic) IBOutlet UITextField *classTextField; 
@property (weak, nonatomic) IBOutlet UITextField *periodTextField; 
@property (strong, nonatomic) Classes *classID; 

- (IBAction)saveClass:(id)sender; 

@end 

ClassTableViewController.m

#import "ClassTableViewController.h" 
#import "Classes.h" 
#import "ClassTableViewCell.h" 
#import "NewClassViewController.h" 

@interface ClassTableViewController() 
- (void)configureCell:(ClassTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath; 
@end 

@implementation ClassTableViewController 


- (id)initWithStyle:(UITableViewStyle)style 
{ 
    self = [super initWithStyle:style]; 
    if (self) { 
     // Custom initialization 
    } 
    return self; 
} 

#pragma mark - Segue 

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { 
    if ([[segue identifier] isEqualToString:@"ShowClass"]){ 
     NewClassViewController *dvc = (NewClassViewController *)[segue destinationViewController]; 
     NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow]; 
     Classes *classID = [[self fetchedResultsController] objectAtIndexPath:indexPath]; 
     [dvc setClassID:classID]; 

    } else if ([[segue identifier] isEqualToString:@"addClass"]) { 
     NewClassViewController *dvc = (NewClassViewController *)[[segue destinationViewController] topViewController]; 
     [dvc setClassID:[NSEntityDescription insertNewObjectForEntityForName:@"Classes" inManagedObjectContext:self.managedObjectContext]]; 
    } 

} 

#pragma mark - View lifecycle 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    // Uncomment the following line to preserve selection between presentations. 
    // self.clearsSelectionOnViewWillAppear = NO; 

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller. 
    // self.navigationItem.rightBarButtonItem = self.editButtonItem; 

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(firstDone)]; 
} 

- (void)viewDidUnload 
{ 
    [super viewDidUnload]; 
    // Release any retained subviews of the main view. 
    // e.g. self.myOutlet = nil; 
} 

- (void) firstDone { 

    [self.navigationController dismissModalViewControllerAnimated: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 [[self.fetchedResultsController sections] count]; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 

    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section]; 

    return [sectionInfo numberOfObjects]; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"ClassesCell"; 

    ClassTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[ClassTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 

    [self configureCell:cell atIndexPath:indexPath]; 

    return cell; 
} 

- (void)configureCell:(ClassTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath { 
    Classes *classID = [self.fetchedResultsController objectAtIndexPath:indexPath]; 
    cell.classLabel.text = classID.classTitle; 
    cell.periodLabel.text = classID.period; 
} 

#pragma mark - Fetched results controller 

- (NSFetchedResultsController *)fetchedResultsController 
{ 
    if (__fetchedResultsController != nil) { 
     return __fetchedResultsController; 
    } 


    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Classes " inManagedObjectContext:self.managedObjectContext]; 

    [fetchRequest setEntity:entity]; 

    [fetchRequest setFetchBatchSize:20]; 

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"period" ascending:YES]; 
    NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil]; 

    [fetchRequest setSortDescriptors:sortDescriptors]; 

    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Master"]; 
    aFetchedResultsController.delegate = self; 
    self.fetchedResultsController = aFetchedResultsController; 

    NSError *error = nil; 

    if (![self.fetchedResultsController performFetch:&error]) { 
     /* 
     Replace this implementation with code to handle the error appropriately. 

     abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
     */ 
     NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
     abort(); 
    } 

    return __fetchedResultsController; 


} 

- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller { 
    [self.tableView beginUpdates]; 
} 


- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo 
      atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type { 

    switch(type) { 
     case NSFetchedResultsChangeInsert: 
      [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] 
          withRowAnimation:UITableViewRowAnimationFade]; 
      break; 

     case NSFetchedResultsChangeDelete: 
      [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] 
          withRowAnimation:UITableViewRowAnimationFade]; 
      break; 
    } 
} 


- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject 
     atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type 
     newIndexPath:(NSIndexPath *)newIndexPath { 

    UITableView *tableView = self.tableView; 

    switch(type) { 

     case NSFetchedResultsChangeInsert: 
      [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] 
          withRowAnimation:UITableViewRowAnimationFade]; 
      break; 

     case NSFetchedResultsChangeDelete: 
      [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] 
          withRowAnimation:UITableViewRowAnimationFade]; 
      break; 

     case NSFetchedResultsChangeUpdate: 
      [self configureCell:[tableView cellForRowAtIndexPath:indexPath] 
        atIndexPath:indexPath]; 
      break; 

     case NSFetchedResultsChangeMove: 
      [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] 
          withRowAnimation:UITableViewRowAnimationFade]; 
      [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] 
          withRowAnimation:UITableViewRowAnimationFade]; 
      break; 
    } 
} 


- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller { 
    [self.tableView endUpdates]; 
} 

/* 
// Override to support conditional editing of the table view. 
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    // Return NO if you do not want the specified item to be editable. 
    return YES; 
} 
*/ 

/* 
// Override to support editing the table view. 
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if (editingStyle == UITableViewCellEditingStyleDelete) { 
     // Delete the row from the data source 
     [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
    } 
    else if (editingStyle == UITableViewCellEditingStyleInsert) { 
     // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view 
    } 
} 
*/ 

/* 
// Override to support rearranging the table view. 
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath 
{ 
} 
*/ 

/* 
// Override to support conditional rearranging of the table view. 
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    // Return NO if you do not want the item to be re-orderable. 
    return YES; 
} 
*/ 

/* 
#pragma mark - Navigation 

// In a story board-based application, you will often want to do a little preparation before navigation 
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{ 
    // Get the new view controller using [segue destinationViewController]. 
    // Pass the selected object to the new view controller. 
} 

*/ 

@end 
+0

В чем конкретно заключается проблема? – RyanR

+0

@Mayankmmmx - У вас все еще проблема? Вы не отправили сообщение об ошибке. Обратная связь необходима, если вы ожидаете ответа, пожалуйста, сообщите. –

ответ

0

Спасибо за предоставление какой-то код и требует какой-либо обратной связи. Файл заголовка запутан для меня. Я рекомендую вам пройти через учебник по этому site.

Вот фрагмент, который поможет вам начать работу, но прохождение кода на сайте - лучший выбор. Впоследствии вы можете вернуться с конкретными вопросами, и я буду рад следить за ними. Если учебник достаточно, чтобы вы пошли, пожалуйста, не стесняйтесь принять этот ответ.

- (NSFetchedResultsController *)fetchedResultsController { 

    if (_fetchedResultsController != nil) { 
     return _fetchedResultsController; 
    } 

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 
    NSEntityDescription *entity = [NSEntityDescription 
     entityForName:@"FailedBankInfo" inManagedObjectContext:managedObjectContext]; 
    [fetchRequest setEntity:entity]; 

    NSSortDescriptor *sort = [[NSSortDescriptor alloc] 
     initWithKey:@"details.closeDate" ascending:NO]; 
    [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]]; 

    [fetchRequest setFetchBatchSize:20]; 

    NSFetchedResultsController *theFetchedResultsController = 
     [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest 
      managedObjectContext:managedObjectContext sectionNameKeyPath:nil 
      cacheName:@"Root"]; 
    self.fetchedResultsController = theFetchedResultsController; 
    _fetchedResultsController.delegate = self; 

    return _fetchedResultsController; 

} 
Смежные вопросы