4

当用户按下Edit时,我的UITableView在顶部添加一个插入行(带有绿色加号),并将所有其他行放入删除模式(红色减号)。或者,用户可以轻扫即可删除而无需按下编辑按钮。我使用几个Ivars来跟踪表格是否处于编辑模式,或者按下编辑按钮,并相应地执行操作(例如,更新numberOfRowsInTableView:当按下Edit时更多插入行)。为什么我不能删除我的UITableView的底部行?

除了事物之外,一切都很完美:在编辑模式下(即用户明确地点击编辑按钮,插入行出现在顶部),如果用户试图删除底行,则下一行取而代之的是删除。删除任何其他行很好。

编辑 - 它似乎删除上面的行,但如果我立即退出,并重新加载应用程序,它原来的底行已经毕竟。所以我猜我的UITableView与我的NSFetchedResultsController不同步。

下面是我使用的代码:

#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; 
    } 
    return self; 
} 

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

#pragma mark - View lifecycle 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    editingFromSwipe = NO; 
    tableIsEditing = NO; 
    self.navigationItem.rightBarButtonItem = self.editButtonItem;  
    self.tableView.allowsSelectionDuringEditing = YES; 
} 


- (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 
{ 
    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section]; 
    int rows = [sectionInfo numberOfObjects]; 

    if (self.editing) { 
     if (!editingFromSwipe && tableIsEditing) { 
      return rows +1; 
     } 
     return rows; 
    } 
    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; 
} 

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

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

     // Save the context. 
     NSError *error = nil; 
     if (![context save:&error]) 
     { 
      // TO DO: Fix error code. 
      NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
      abort(); 
     } 
    }  
    else if (editingStyle == UITableViewCellEditingStyleInsert) { 
     [self addingView];   
    } 
} 

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

    if (self.editing && row == 0) { 
     if (!editingFromSwipe && tableIsEditing) { 
      return UITableViewCellEditingStyleInsert; 
     } 
     else if (editingFromSwipe) { 
      return UITableViewCellEditingStyleDelete; 
     } 

    } 
    return UITableViewCellEditingStyleDelete; 
} 


- (void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    editingFromSwipe = YES; 
    [super tableView:tableView willBeginEditingRowAtIndexPath:indexPath]; 
} 

- (void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    [super tableView:tableView didEndEditingRowAtIndexPath:indexPath]; 
    editingFromSwipe = NO; 
} 


- (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) { 
      tableIsEditing = YES; 
      [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) { 
     TO DO: Code for when row is selected 
    } 
} 


#pragma mark - Data 


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


- (void) addingView// :(id)sender 
{ 
    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]) 
     { 
      TO DO: fix error code. 
      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]) 
    { 
     // TO DO: error stuff 
     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]; 
} 

@end 
+0

下一次您要发布378行代码时,只需提供指向文件的链接即可。 – TechZen 2011-03-25 21:00:19

+0

我会告诫你不要让你的tableviews复杂。我认为试图编辑tableview单元格内的数据几乎总是一个错误。在桌面视图中还有很多事情要做,以便进行编辑。要创建一个新行,请使用详细视图。这就是界面语法教会用户所期望的。 – TechZen 2011-03-26 15:37:14

+0

@TechZen请原谅我对术语的陌生感,但是通过使用细节视图,你的意思是什么?我将'detail view'与加载全新视图(例如,当用户选择父项时加载子实体表)相关联。我如何将一行添加到具有详细视图的表格中? – 2011-03-27 12:30:24

回答

1

你的过错设计它。你不应该在任何地方添加行,而是在逻辑上将它们放在表中。

抓取结果控制器(FRC)的整个点是使表视图与数据同步。表中的行顺序应反映fetchedObjects数组中的管理对象的顺序。通过在底部或顶部插入一行,并添加一个不一定在逻辑上属于该表顶部或底部的对象,正在打破该同步。

当您在addingViewController:didAdd:中添加新的托管对象时,FRC会提示它尝试重新绘制表格。你试图弥补这一点,但你真的不能。你所有的索引都会出来。

而不是使用一行来输入新行。使用tableview页眉或页脚视图。这样,您可以冻结tableview,创建新对象,然后更新表格,新对象将显示表格中逻辑所属的位置。

+0

谢谢。作为一个新手,我不知道可以用表头做到这一点,但有一点谷歌搜索似乎证实我应该能够在那里贴一个按钮,并以更优雅的方式处理这个按钮。我怀疑我以前看过的使用插入行的例子一定没有使用过NSFetchedResultsController,那可能是我陷入困境的地方。当我回到我的身边时,我会试试这个,然后我会回到这里,让你知道我是怎么做到的。 – 2011-03-25 22:06:28

+0

它工作完美!我发现[本指南](http://osmorphis.blogspot.com/2009/04/putting-button-in-table.html)向表格添加按钮,并且大约需要5分钟才能实现。我也可以按照这种方式自定义按钮,如果我更换我的表格,它应该可以轻松地“缩放”。谢谢! – 2011-03-28 14:41:10

1

为了不把行混在一起,我建议把插入行放在它自己的部分。既然你明明只是使用一个部分中,您知道您发送到FRC部分应始终为0的代码是一样简单:

[context deleteObject:[self.fetchedResultsController objectAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row inSection:0]]]; 

TechZen的解决方案也将工作,所以你选择哪种解决方案完全关于你喜欢什么样的设计。 TechZen的解决方案不会影响到多个部分,但是此解决方案也可以修改以支持多个部分。

+0

非常感谢你的帮助Erik。最后,我已经使用了TechZen的建议,但在过去的几天里我已经从您那里学到了很多金额,而且我的一般编程知识对它来说更好! – 2011-03-28 14:39:31

2

您可以将静态单元添加到从NSFetchedResultsController获取其数据的UITableViews。但要做到这一点,您必须调整几乎所有在UITableViewDelegateUITableViewDataSourceNSFetchedResultsControllerDelegate方法之一中使用的NSIndexPath。

我添加了一些帮助器方法,将tableview的indexpath转换为抓取的resultscontroller的indexpath,反之亦然。

- (NSIndexPath *)tableIndexPathFromNSFRCIndexPath:(NSIndexPath *)ip { 
    if (editingMode && ip.section == 0) { 
     NSIndexPath *newIP = [NSIndexPath indexPathForRow:ip.row+1 inSection:ip.section]; 
     return newIP; 
    } 
    return ip; 
} 

- (NSIndexPath *)nsfrcIndexPathFromTableIndexPath:(NSIndexPath *)ip { 
    if (editingMode && ip.section == 0) { 
     NSIndexPath *newIP = [NSIndexPath indexPathForRow:ip.row-1 inSection:ip.section]; 
     return newIP; 
    } 
    return ip; 
} 

,然后你不得不改变每一个通过从表中indexpath到fetchedresultscontroller或从FRC表方法:像这样的东西可以,如果你想在上面添加行使用。我以两个为例。

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject 
     atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type 
     newIndexPath:(NSIndexPath *)newIndexPath { 
    newIndexPath = [self tableIndexPathFromNSFRCIndexPath:newIndexPath]; 
    indexPath = [self tableIndexPathFromNSFRCIndexPath:indexPath]; 
    switch(type) { 
     case NSFetchedResultsChangeInsert: 
      [self.listTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade]; 
      break; 
     case NSFetchedResultsChangeDelete: 
      [self.listTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
      break; 
     case NSFetchedResultsChangeUpdate: 
      [self configureCell:[self.listTableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath]; 
      break; 
     case NSFetchedResultsChangeMove: 
      [self.listTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
      [self.listTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]withRowAnimation:UITableViewRowAnimationFade]; 
      break; 
    } 
} 

- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ 
    [aTableView deselectRowAtIndexPath:indexPath animated:YES]; 
    if (editingMode && indexPath.section == 0 && indexPath.row == 0) { 
     // Add New entry... 
    } 
    else { 
     indexPath = [self nsfrcIndexPathFromTableIndexPath:indexPath]; 
     NSManagedObject *selectedObject = [self.fetchedResultsController objectAtIndexPath:indexPath]); 
    } 
} 
+0

谢谢Fluchpunkt! – 2011-03-28 14:43:20

相关问题