1

所以我一直在寻找这个我遇到的有趣问题的答案,但运气不太好。基本上,我在初始应用程序启动时预加载了一个 UITableView,其中包含一些使用 CoreData 的对象,以及用户添加更多对象的能力。

我允许删除表格中的单元格,除了我最初预加载的项目。因此,我在我的 canEditRowAtIndexPath 方法中执行检查,如果所选项目是这些预加载项目之一,则返回 NO。一切都很好,直到我向下滚动到足以让其中一个项目离开屏幕,然后当它重新捕捉不应编辑的项目时,现在可以编辑了。

我对 iOS 开发相当陌生,所以我希望这是一个相当业余的问题 - 但我似乎找不到答案。

任何帮助表示赞赏。

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
 {
     DataLayer *dl = [DataLayer alloc];

     // Get all items from Favorites
     NSArray *results = [dl FetchAll:@"Favorites"];

     // Get currently selected cell properties
     FavoritesTableCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
     Favorites *fav = [Favorites alloc];
     NSMutableArray *genItems = [[NSMutableArray alloc] init];

     // Get only records that are default app items
     for(int a = 0; a < [results count]; a++){
         fav = [results objectAtIndex:a];

         if ([fav.generic isEqualToNumber:[NSNumber numberWithInt:1]]) {
             [genItems addObject:fav];
         }
     }

     // Loop through default items to determine if editable
     for (int i = 0; i < [genItems count]; i++) {
         fav = [genItems objectAtIndex:i];

         if ([fav.title isEqualToString:[selectedCell.nameLabel text]]) {
             return NO;
         }
     }
     return YES;
 }
4

1 回答 1

2

问题的根源在于,这种方法的答案是基于表格视图单元格 ( selectedCell) 的内容而不是模型。

表视图重用单元格。当它们从视图中滚动出来时,出现的“新”单元格实际上是刚刚在表格另一侧消失的同一个对象。因此,对于应该放在模型中的问题, selectedCell 并不是一个很好的参考。

代码的结构需要像这样:

您的模型是一个 NSMutableArray,它以您添加的一些项目开头。您需要知道哪些项目是原件,而不是被删除:

@property (nonatomic, strong) NSMutableArray *favorites;
@property (nonatomic, assign) NSMutableArray *genericFavorites;

// at init, imagine these strings are your preloaded core data

[self.genericFavorites addObject:@"generic favorite object a"];
[self.genericFavorites addObject:@"generic favorite object b"];
[self.favorites addItemsFromArray:self.genericFavorites];

您将self.favorites用作模型,即当表格视图询问时numberOfRowsInSection,您将回答self.favorites.count。在cellForRowAtIndexPath中,您将在 中查找项目self.favorites[indexPath.row]并使用来自该对象的数据配置单元格。 self.genericFavorites只是帮助您记住哪些对象是原始的,而不是用户添加的。

如果订单保持不变,那么您的 canEditRow 逻辑很简单:

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
    return indexPath.row >= self.genericFavorites.count;
}

但是,如果,正如您的代码所暗示的那样,用户可以重新排序这些项目,那么您的 canEditRow 有更多工作要做,但它可以在不参考表格单元格的情况下完成这项工作(正如我所指出的那样,这是不可靠的):

// get the object at indexPath.row from our model.  Answer NO if that object was preloaded
// from the app (if genericFavorites containsObject:), YES otherwise

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath

    Favorite *favorite = self.favorites[indexPath.row];   // this is your model after user has edited, reordered, etc
    return ![self.genericFavorites containsObject:favorite];
}
于 2013-10-17T05:10:22.333 回答