My UITableView has an Edit button which adds an "insert row" (with a green plus). If I try to delete a row while in Edit mode, my app crashes with "NSRangeException". Deleting a row while NOT in edit mode (using swipe-to-delete) is fine.
I know this is to do with how many rows the table view thinks it has - getting an insert row and swipe-to-delete both to work in the same table is a nightmare (for a beginner like me) because both swiping and pressing the edit button put the table in "edit mode", but the edit button adds a row, whereas swiping doesn't.
I've been trying to use a couple of Ivars to overcome this, but clearly I've gone wrong somewhere. Can someone more experienced tell me where I'm going wrong? (I'm sure I'm going about this in far too complicated a way!).
EDIT - as requested by Chiefly Izzy, I've put my whole unedited .m file here.
//
// 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
EDIT: Here is the new code in my 'tableView:commitEditingStyle:forRowAtIndexPath' method, based on Erik B's advice:
- (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
}
}
The app no longer crashes, and swipe-to-delete is still fine, but if try to delete the last row while in Edit mode, it deletes the second-last row instead. All the other rows are fine. (My insert row is at the top, incidentally).
So this is what we know: You get NSRangeException
on this line:
[context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];
deleteObject:
doesn't throw NSRangeException
, so we know that
[self.fetchedResultsController objectAtIndexPath:indexPath]
is causing the crash. The most probable cause for this is that you don't take into account that the table view's index path isn't the same as the fetchedResultsController
's index path when you have added the "insert row".
If I'm right it should only crash when you delete the last row.
This is how you fix it:
[self.fetchedResultsController objectAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row-1 inSection:indexPath.section]]
Keep in mind that you should only change the index path if the "insert row" is visible.
EDIT:
Deleting the row just below the insert row works fine. I can delete any row with swipe-to-delete, and using the edit button I can delete any row except the last row (which deletes the row above it instead).
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]];
}
So this is what's causing that bug:
numberOfRows == rowBeingDeleted
You only change the index path if it's the last row. This is confusing, but maybe you shouldn't change the index path then? Try replacing numberOfRows == rowBeingDeleted
with NO
and see what happens.
EDIT 2: What happens if you do this instead?
if (tableIsEditing && !editingFromSwipe) {
[context deleteObject:[self.fetchedResultsController objectAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row-1 inSection:indexPath.section]]];
} else {
[context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];
}
精彩评论