我为我的应用程序设置了此代码,该代码具有与记事本类似的功能:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
// Set ignoreDefaultsChanged to YES so that the defaultsChanged method won't interfere with the deletion of a summary
ignoreDefaultsChanged = YES;
// OUT OF BOUNDS ERROR
[_objects removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
// Delete the associated information
[[NSUserDefaults standardUserDefaults] removeObjectForKey:[NSString stringWithFormat:@"%@%@", _objects[indexPath.row], @"-summary"]];
// Save the new list of combined summaries
[[NSUserDefaults standardUserDefaults] setObject:_objects forKey:@"prepareKey"];
}
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.
}
}
- (void)defaultsChanged:(NSNotification *)notification {
if (ignoreDefaultsChanged == YES)
{
// Do nothing
}
else if (ignoreDefaultsChanged == NO)
{
// Setup savingKey
savingKey = @"prepareKey";
// Load the items from NSUserDefaults
_objects = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:savingKey]];
// Reload the tableView
[self.tableView reloadData];
}
}
- (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.leftBarButtonItem = self.editButtonItem;
// Register a class or nib file using registerNib:forCellReuseIdentifier
// o registerClass:forCellReuiseIdentifier: method before calling this method
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
// Setup savingKey
savingKey = @"prepareKey";
// Load the items from NSUserDefaults
_objects = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:savingKey]];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(defaultsChanged:) name:NSUserDefaultsDidChangeNotification object:nil];
}
如果我现在尝试删除最底部的单元格,应用程序会崩溃并显示以下消息:
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 2 beyond bounds [0 .. 5]'
有关如何解决此问题的任何想法?