向tableview添加行以添加行和核心数据

时间:2011-09-03 01:23:14

标签: uitableview core-data

我创建了一个使用核心数据的基于导航控制器的应用程序。如果不首先修改起始应用程序中的大部分代码,我希望能够通过在推送编辑后通过动态行添加行来添加行。

我发现的其他示例(例如在this site找到的示例显示了所需的功能,但它不使用核心数据,因此我无法使用核心数据正确翻译。

我查看了示例应用程序iPhoneCoreDataRecipes,该应用程序包含所需的功能,但样本非常复杂。基于示例应用程序,我已将以下内容添加到我的 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath函数

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{


static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// For the Ingredients section, if necessary create a new cell and configure it with an additional label for the amount.  Give the cell a different identifier from that used for cells in other sections so that it can be dequeued separately.
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:0];

NSInteger rows = [sectionInfo numberOfObjects]; 
NSUInteger ingredientCount = rows;
NSInteger row = indexPath.row;

if (indexPath.row < ingredientCount) {
    // If the row is within the range of the number of ingredients for the current recipe, then configure the cell to show the ingredient name and amount.
    static NSString *IngredientsCellIdentifier = @"IngredientsCell";

    cell = [tableView dequeueReusableCellWithIdentifier:IngredientsCellIdentifier];

    if (cell == nil) {
        // Create a cell to display an ingredient.
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:IngredientsCellIdentifier] autorelease];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }

   // 
    [self configureCell:cell atIndexPath:indexPath];
} else {
    // If the row is outside the range, it's the row that was added to allow insertion (see tableView:numberOfRowsInSection:) so give it an appropriate label.
    NSLog(@"---- IN ADD INGREDIENTS SECTION ----");
    static NSString *AddIngredientCellIdentifier = @"AddIngredientCell";

    cell = [tableView dequeueReusableCellWithIdentifier:AddIngredientCellIdentifier];
    if (cell == nil) {
        // Create a cell to display "Add Ingredient".
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:AddIngredientCellIdentifier] autorelease];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    cell.textLabel.text = @"Add Ingredient";
}
return cell;
}

当我单击编辑按钮时,我可以删除行,但是我没有获得添加的行来单击以添加行。示例应用程序很复杂,以告诉我缺少什么。是否有一个函数可以添加以自动添加表格末尾的“添加行”按钮?

编辑:添加了我的所有.M文件以供参考@ http://pastebin.com/Ld7kVts7 当我在控制台中运行NSLog的1-12节目时。我目前没有尝试将“添加行”行添加到核心数据,因为每次用户按下导航栏中的编辑按钮时都会添加或删除该行。

2 个答案:

答案 0 :(得分:0)

您是否更改了数据源的numberOfRowsInSection方法以占用您需要的额外行?

答案 1 :(得分:0)

您需要做的是将新对象添加到数据库中,然后,假设您的tableView的dataSource是数据库中的数组,请在tableView上调用reloadData。

相关问题