2013-08-13 3 views
-1

Я пытаюсь удалить основную запись данных из моего контроллера табличного представления, так что, когда я прокручиваю влево, появляется кнопка удаления и удаляет запись. К сожалению, я получаю сообщение об ошибке: «Свойство« Классы »не найдено в типе« ClassTableViewController * »в строке 251 и 260 (код указан ниже) и я не уверен, что делать. У меня есть класс NSMutableObject под названием Classes.m и классы .h, и они были импортированы, но Xcode, кажется, не признают егоУдаление ввода основных данных из контроллера табличного представления

Вот код:.

ClassTableViewController.m

#import "ClassTableViewController.h" 
#import "Classes.m" 
#import "Classes.h" 
#import "ClassTableViewCell.h" 
#import "NewClassViewController.h" 
#import <CoreData/CoreData.h> 

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

@implementation ClassTableViewController 

@synthesize fetchedResultsController = _fetchedResultsController; 
@synthesize managedObjectContext = _managedObjectContext; 
@synthesize managedObjectModel = _managedObjectModel; 


- (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:@"MyClassesID" 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)]; 

    if (_managedObjectContext == nil) 
    { 
     _managedObjectContext = [(ClassTableViewController *)[[UIApplication sharedApplication] delegate] managedObjectContext]; 
     NSLog(@"After managedObjectContext: %@", _managedObjectContext); 
    } 


} 

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

#pragma mark - Table view delegate 


- (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:@"MyClassesID" inManagedObjectContext:self.managedObjectContext]; 
    assert(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]; 
} 

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


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    NSManagedObjectContext *context = [self managedObjectContext]; 

    if (editingStyle == UITableViewCellEditingStyleDelete) { 
     // Delete object from database 
     [context deleteObject:[self.Classes objectAtIndex:indexPath.row]]; 

     NSError *error = nil; 
     if (![context save:&error]) { 
      NSLog(@"Can't Delete! %@ %@", error, [error localizedDescription]); 
      return; 
     } 

     // Remove device from table view 
     [self.Classes removeObjectAtIndex:indexPath.row]; 
     [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
    } 
} 

/* 
// 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 

код, в котором я получаю ошибка:

Линия 251:

[context deleteObject:[self.Classes objectAtIndex:indexPath.row]]; 

Line 260:

[self.Classes removeObjectAtIndex:indexPath.row]; 
+1

вы можете поместить код для 'ClassTableViewController.h '? –

+1

Это необоснованное количество кода. – dandan78

ответ

3

Прежде всего, удалите #import "Classes.m". Во-вторых, я полагаю, self.Classes массив, который поднимает два вопроса:

  1. Если ваш класс называется Classes, то почему ваша переменная с именем Classes а? Переименуйте переменную в vClasses или aClasses или classes. Кроме того, убедитесь, что self.classes (или в вашем случае self.Classes) инициализируется правильно. Отлаживать!
  2. Почему вы используете массив для объектов Classes, если у вас есть NSFetchedResultsController настройка? Вместо этого вы должны использовать self.fetchedResultsController.

Надеюсь, что это поможет.

+0

Это все отличные моменты и должно помочь вам отладить проблему. –

+0

Я не использую self.Classes как массив, а скорее NSMutableObject, чтобы он удалялся. Это мой первый раз, когда я пытаюсь это сделать, поэтому я точно не знаю, как это работает. Я попытался изменить его на self.NSFetchedResultsController, но я получил ошибку: Нет видимого @interface для 'NSFetchedResultsController' объявляет селектор 'removeObjectAtIndex' – Mayankmmmx

+0

Я думаю, что вам нужно что-то сделать, прежде чем что-либо еще, прочитать о NSArray, NSMutableArray , NSFetchedResultsController, UITableView, UIViewController и UITableViewController. Ваши вопросы подсказывают, что вам необходимо изучить основы. Попробуйте онлайн-блоги, книгу по разработке приложений для iOS, OR (рекомендуется), чтобы проверить публикации Стэнфордских лекций (бесплатно) или iPhone Development Videos от Apple на iTunes. – Mustafa

0

Ошибка довольно ясна, нет свойства с именем «Classes» в этом классе, конечно, вы импортировали класс с именем Classes, но это не переменная property/instance. По крайней мере, не то, что я вижу ...

[self.Classes removeObjectAtIndex:indexPath.row]; 

Эта линия не имеет смысла, вы должны сообщать свой источник данных, чтобы удалить объект ...

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