UITableView в режиме редактирования - нажатие кнопки Delete приводит к сбою приложения - PullRequest
2 голосов
/ 23 марта 2011

Мой UITableView имеет кнопку «Редактировать», которая добавляет «вставить строку» (с зеленым плюсом).Если я пытаюсь удалить строку в режиме редактирования, мое приложение вылетает с «NSRangeException».Удалять строку, находясь НЕ в режиме редактирования (с помощью операции «смахивание»), можно.

Я знаю, что это связано с тем, сколько строк, по мнению табличного представления, - получение строки вставки и смахивание к- удаление обоих для работы в одной и той же таблице является кошмаром (для начинающего, такого как я), потому что при пролистывании и нажатии на кнопку редактирования переводит таблицу в «режим редактирования», но кнопка редактирования добавляет строку, а смахивание - нет.

Я пытался использовать пару ивар для преодоления этого, но, очевидно, я где-то ошибся.Может кто-нибудь более опытный сказать мне, где я иду не так?(Я уверен, что я собираюсь сделать это слишком сложным способом!).

РЕДАКТИРОВАТЬ - в соответствии с просьбой Главли Иззи, я поместил весь свой неотредактированный файл .m здесь.

//
//  ChecklistsViewController.m
//  Check Box
//
//  Created by Ric on 18/03/2011.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ChecklistsViewController.h"
#import "Checklist.h"

@interface ChecklistsViewController (private)
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath;
- (void)addingView;
@end


@implementation ChecklistsViewController

@synthesize category, managedObjectContext, fetchedResultsController;


- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        editingFromSwipe = NO;
        tableIsEditing = NO;
        NSLog(@"tableIsEditing = NO (init) \n");
        NSLog(@"Not Editing From Swipe (init) \n");
    }
    return self;
}

- (void)dealloc
{
    [category release];
    [managedObjectContext release];
    [fetchedResultsController release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    editingFromSwipe = NO;
    tableIsEditing = NO;
    NSLog(@"tableIsEditing = NO (viewDidLoad) \n");
    NSLog(@"Not Editing From Swipe (viewDidLoad) \n");

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

    self.navigationItem.rightBarButtonItem = self.editButtonItem;    
    self.tableView.allowsSelectionDuringEditing = YES;
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [[self.fetchedResultsController sections] count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"numberOfRowsInSection HAS BEEN CALLED");
    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
    int rows = [sectionInfo numberOfObjects];

    if (self.editing) {
        if (!editingFromSwipe && tableIsEditing) {
            NSLog(@"Returning extra row - editing not from swipe \n");
            return rows +1;
        }
        NSLog(@"Returning normal rows - editing from swipe \n");
        return rows;
    }
    NSLog(@"Returning normal rows - not editing - and setting tableIsEditing back to NO \n"); 
    tableIsEditing = NO;
    return rows;
}

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell...
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;


    NSLog(@"Should go into if statement here! \n");

    if (tableView.editing) { //
        if ((indexPath.row == 0) && (!editingFromSwipe)) {
            NSLog(@"Configuring Add Button Cell while editing \n");
            cell.textLabel.text = @"Add New Checklist";
            cell.detailTextLabel.text = nil;
        }
        else {
            NSLog(@"Configuring other cells while editing \n");
            [self configureCell:cell atIndexPath:indexPath];
        }

    }
    else {
        NSLog(@"Configuring Cell Normally While Not Editing \n");
        [self configureCell:cell atIndexPath:indexPath];
    }


    return cell;
}


// Override to support conditional editing of the table view.
/*
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // return (indexPath.row != 0);
    return YES;
}
*/


// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        // Delete the managed object for the given index path
        NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];        
        [context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];

        // Save the context.
        NSError *error = nil;
        if (![context save:&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. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
             */
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }    
    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
        [self addingView];

    }   
}


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

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    int row = indexPath.row;

    if (self.editing && row == 0) {
        if (!editingFromSwipe && tableIsEditing) {
            NSLog(@"Not from swipe so making first row style insert button \n");
            return UITableViewCellEditingStyleInsert;
        }
        else if (editingFromSwipe) { 
            NSLog(@"Is from swipe so making first row delete rather than insert \n");
            return UITableViewCellEditingStyleDelete;
        }

    }
    NSLog(@"Not editing or not first row so making cell style normal \n");
    return UITableViewCellEditingStyleDelete;
}


- (void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    editingFromSwipe = YES;
    // NSLog(@"Editing From Swipe (just swiped) \n");
    [super tableView:tableView willBeginEditingRowAtIndexPath:indexPath];
}

- (void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    [super tableView:tableView didEndEditingRowAtIndexPath:indexPath];
    editingFromSwipe = NO;
    // NSLog(@"Not Editing From Swipe (just unswiped) \n");
}


- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];

    NSArray *addRow = [NSArray arrayWithObjects:[NSIndexPath indexPathForRow:0 inSection:0], nil];
    [self.tableView beginUpdates];

    if (!editingFromSwipe) {
        if (editing) {
            NSLog(@"Editing called while swipe off, so adding insert row \n");
            tableIsEditing = YES;
            NSLog(@"tableIsEditing = YES (setEditing:Animated:)");
            [self.tableView insertRowsAtIndexPaths:addRow withRowAnimation:UITableViewRowAnimationLeft];
        }
        else {
            [self.tableView deleteRowsAtIndexPaths:addRow withRowAnimation:UITableViewRowAnimationLeft];
        } 
    }
    [self.tableView endUpdates];
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row != 0) {
        // Navigation logic may go here. Create and push another view controller.
        /*
         <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
         // ...
         // Pass the selected object to the new view controller.
         [self.navigationController pushViewController:detailViewController animated:YES];
         [detailViewController release];
         */
    }
}


#pragma mark - Data


- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    Checklist *aChecklist = [self.fetchedResultsController objectAtIndexPath:indexPath];
    cell.textLabel.text = aChecklist.name; // description];
    cell.detailTextLabel.text = aChecklist.category.name; // description];
}


- (void) addingView// :(id)sender
{
    // Turn off edit mode if it is on.
    //if (self.editing) {
    //    [self.navigationController setEditing:NO animated:YES];
    //}

    //Create the root view controller for the navigation controller
    AddingViewController *viewController = [[AddingViewController alloc] initWithNibName:@"AddingViewController" bundle:nil];

    viewController.delegate = self;
    viewController.title = @"Add Checklist";

    // Create the navigation controller and present it modally
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
    [self presentModalViewController:navigationController animated:YES];

    viewController.textLabel.text = @"Enter new checklist name";

    [navigationController release];
    [viewController release];
}


#pragma mark - AddingViewDelegate


- (void)addingViewController:(AddingViewController *)addingViewController didAdd:(NSString *)itemAdded
{
    if (itemAdded != nil) {

        // Turn off editing mode.
        if (self.editing) [self.navigationController setEditing:NO animated:NO];

        // Add the category name to our model and table view.

        // Create a new instance of the entity managed by the fetched results controller.
        NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
        NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
        Checklist *newChecklist = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];

        [category addChecklistsObject:newChecklist];

        newChecklist.name = itemAdded;        
        // [newChecklist setDateStamp:[NSDate date]];

        // Save the context.
        NSError *error = nil;
        if (![context save:&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. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
             */
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }


    }

    [self dismissModalViewControllerAnimated:YES];
}


#pragma mark - Fetched results controller

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

    // Set up the fetched results controller.

    // Create the fetch request for the entity.
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    // Edit the entity name as appropriate.
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Checklist" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Set 4* the predicate so we only see checklists for this category.
    NSPredicate *requestPredicate = [NSPredicate predicateWithFormat:@"category.name = %@", self.category.name];
    [fetchRequest setPredicate:requestPredicate];    
    // Set the batch size to a suitable number.
    [fetchRequest setFetchBatchSize:20];    
    // Edit the sort key as appropriate.
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    [fetchRequest setSortDescriptors:sortDescriptors];    
    // Edit the section name key path and cache name if appropriate.
    // nil for section name key path means "no sections".    

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


    [aFetchedResultsController release];
    [fetchRequest release];
    [sortDescriptor release];
    [sortDescriptors release];

    NSError *error = nil;
    if (![self.fetchedResultsController performFetch:&error])
    {
       // handle the error properly!
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return fetchedResultsController;
} 


#pragma mark - Fetched results controller delegate


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


/*
 // Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed. 

 - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
 {
 // In the simplest, most efficient, case, reload the table view.
 [self.tableView reloadData];
 }
 */




@end


РЕДАКТИРОВАТЬ: Вот новый код в моем методе 'tableView: commitEditingStyle: forRowAtIndexPath', основанный на совете Эрика Б.:

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

        int numberOfRows = [self tableView:tableView numberOfRowsInSection:indexPath.section];
        int rowBeingDeleted = indexPath.row +1;

        if (tableIsEditing && !editingFromSwipe && numberOfRows == rowBeingDeleted) {
            [context deleteObject:[self.fetchedResultsController objectAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row-1 inSection:indexPath.section]]];
        }
        else {
            [context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];
        }

        // context saving code    
    }      
}

Приложениебольше не вылетает, и смахивание для удаления все еще в порядке, но если попытаться удалить последнюю строку в режиме редактирования, она удалит вторую последнюю строку.Все остальные ряды в порядке.(Моя строка вставки вверху, между прочим).

1 Ответ

4 голосов
/ 24 марта 2011

Итак, это то, что мы знаем: вы получаете NSRangeException в этой строке:

[context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];

deleteObject: не бросает NSRangeException, поэтому мы знаем, что

[self.fetchedResultsController objectAtIndexPath:indexPath]

вызывает сбой. Наиболее вероятная причина этого заключается в том, что вы не учитываете, что путь индекса табличного представления не совпадает с путем индекса fetchedResultsController, когда вы добавили «строку вставки».

Если я прав, это может произойти только при удалении последней строки.

Вот как это исправить:

[self.fetchedResultsController objectAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row-1 inSection:indexPath.section]]

Имейте в виду, что вам следует изменять путь индекса только в том случае, если видна «строка вставки».

EDIT:

Удаление строки чуть ниже строки вставки работает нормально. Я могу удалить любую строку с помощью пролистывания для удаления, и с помощью кнопки редактирования я могу удалить любую строку, кроме последней (которая вместо этого удаляет строку над ней).

if (tableIsEditing && !editingFromSwipe && numberOfRows == rowBeingDeleted) {
    [context deleteObject:[self.fetchedResultsController objectAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row-1 inSection:indexPath.section]]];
} else {
    [context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];
}

Так вот что вызывает эту ошибку:

numberOfRows == rowBeingDeleted

Вы можете изменить путь индекса, только если это последняя строка. Это сбивает с толку, но, может быть, вам не следует менять путь индекса? Попробуйте заменить numberOfRows == rowBeingDeleted на NO и посмотрите, что получится.

РЕДАКТИРОВАТЬ 2: Что произойдет, если вы сделаете это вместо этого?

if (tableIsEditing && !editingFromSwipe) {
    [context deleteObject:[self.fetchedResultsController objectAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row-1 inSection:indexPath.section]]];
} else {
    [context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...