jjzjj

iphone - 删除最后一条记录时 UITableView deleteRowsAtIndexPath 崩溃

coder 2023-07-27 原文

当我从 UITableView 中删除最后一条记录时遇到以下错误。

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (3) must be equal to the number of rows contained in that section before the update (1), plus or minus the number of rows inserted or deleted from that section (1 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

我的目标是在表格数组为空时显示“未找到记录”。

这是我正在使用的代码。当我从表数组中删除最后一条记录时,应用程序崩溃了。如何重新加载表格并显示“未找到记录”标签?

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([idArray count]==0) {
        return  3;
    }
    else 
    {
        return [idArray count];
    }   
}

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

    NSLog(@"array count %d",[idArray count]);
    if ([idArray count] == 0) {
        static NSString *CellIdentifier = @"Cell";

        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }
        cell.textLabel.textAlignment = UITextAlignmentCenter;

        tableView.userInteractionEnabled = NO;

        self.navigationItem.leftBarButtonItem.enabled = NO;
         NSUInteger row = [indexPath row];

        switch (row) {
            case 0:
                cell.textLabel.text = @"";
                break;
            case 1:
                cell.textLabel.text = @"";
                break;

            case 2:
                cell.textLabel.text = @"No Records Found";
                break;


            default:
                break;
        }        

        return cell;
    }
    else
    {   static NSString *CellIdentifier = @"Cell";

        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        }

        tableView.userInteractionEnabled = YES;

        self.navigationItem.leftBarButtonItem.enabled = YES;

        // Set up the cell
        identify *idItems = [idArray objectAtIndex:indexPath.row];

        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"dd MMM,yyyy"];
        NSString *dateStr = [formatter stringFromDate:idItems.Date];
        UIImageView *accDis = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Arrow.png"]];    
        cell.accessoryView = accDis;
        self.idTableView.separatorColor = [UIColor colorWithRed:150.0/255.0 green:150.0/255.0 blue:150.0/255.0 alpha:1];
        cell.textLabel.textColor = [UIColor blackColor];
        cell.textLabel.font = [UIFont boldSystemFontOfSize:18];
        cell.textLabel.adjustsFontSizeToFitWidth = YES;
        cell.detailTextLabel.textColor = [UIColor colorWithRed:100.0/255.0 green:100.0/255.0 blue:100.0/255.0 alpha:1];
        cell.detailTextLabel.font = [UIFont italicSystemFontOfSize:16];
        cell.detailTextLabel.adjustsFontSizeToFitWidth = YES;

        NSString *detailText = [NSString stringWithFormat:@"%@ - %@",dateStr,idItems.GeoCode];

        if (idItems.Image == NULL) {
            cell.imageView.image = [UIImage imageNamed:@"icon58x58.png"];
        }
        else
        {
        //pass image to fix size 50 X 50
        //UIImage *newImage = [self postProcessImage:idItems.Image];
            cell.imageView.image = idItems.thumb;//newImage; 
        cell.imageView.contentMode=UIViewContentModeScaleAspectFill;
        }

        cell.textLabel.text = idItems.TypeName; 
        cell.detailTextLabel.text = detailText;

        return cell;   
    }    
}

- (void)tableView:(UITableView *)tv commitEditingStyle:(UITableViewCellEditingStyle)editingStyle 
    forRowAtIndexPath:(NSIndexPath *)indexPath {

    if(editingStyle == UITableViewCellEditingStyleDelete) {

        if ([idArray count] >=1) 
        {
            [idTableView beginUpdates];

            //Get the object to delete from the array.
            identifyObject = [appDelegate.idArray objectAtIndex:indexPath.row];

            //Delete the object from the table.
            [self.idTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
             [appDelegate removeID:identifyObject];

            if ([idArray count] == 0) {
                [self.idTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            }
            [idTableView endUpdates];
        }
    }
}

最佳答案

问题在于 TableView 期望在 View 上执行的操作与数据源相匹配。您在表中有一条记录,然后将其删除。 tableview 期望数据源现在包含零条记录,但由于您的“未找到记录”逻辑,它实际上返回值 3,因此出现一致性错误和崩溃。

错误似乎是这部分:

if ([idArray count] == 0) {
    [self.idTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}

我假设这是为了在删除最后一行时将“未找到记录”行插入到表中,但是由于您的“未找到记录”实际上跨越三行,因此您需要在此处插入三行,例如这个:

if ([idArray count] == 0) {
    [self.idTableView insertRowsAtIndexPaths:[NSArray arrayWithObjects:
    [NSIndexPath indexPathForRow:0 inSection:indexPath.section],
    [NSIndexPath indexPathForRow:1 inSection:indexPath.section],
    [NSIndexPath indexPathForRow:2 inSection:indexPath.section],
    nil] withRowAnimation:UITableViewRowAnimationFade];
}

然而,为了您的理智,我可以建议一种不同的方法吗?与其试图让你的表和数据源保持同步,同时处理这些仅用于显示目的的假三行数据,不如将 UILabel 插入到你的 View 层次结构中(在 TableView 的前面或后面),上面写着“no records found”并根据表是否有数据显示/隐藏?这样你就可以精确地控制它的位置和外观,而不必搞砸你的数据源逻辑。

关于iphone - 删除最后一条记录时 UITableView deleteRowsAtIndexPath 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8960037/

有关iphone - 删除最后一条记录时 UITableView deleteRowsAtIndexPath 崩溃的更多相关文章

  1. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

  2. ruby - 我可以使用 Ruby 从 CSV 中删除列吗? - 2

    查看Ruby的CSV库的文档,我非常确定这是可能且简单的。我只需要使用Ruby删除CSV文件的前三列,但我没有成功运行它。 最佳答案 csv_table=CSV.read(file_path_in,:headers=>true)csv_table.delete("header_name")csv_table.to_csv#=>ThenewCSVinstringformat检查CSV::Table文档:http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV/Table.html

  3. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  4. Ruby Readline 在向上箭头上使控制台崩溃 - 2

    当我在Rails控制台中按向上或向左箭头时,出现此错误:irb(main):001:0>/Users/me/.rvm/gems/ruby-2.0.0-p247/gems/rb-readline-0.4.2/lib/rbreadline.rb:4269:in`blockin_rl_dispatch_subseq':invalidbytesequenceinUTF-8(ArgumentError)我使用rvm来管理我的ruby​​安装。我正在使用=>ruby-2.0.0-p247[x86_64]我使用bundle来管理我的gem,并且我有rb-readline(0.4.2)(人们推荐的最少

  5. ruby - 我可以使用 aws-sdk-ruby 在 AWS S3 上使用事务性文件删除/上传吗? - 2

    我发现ActiveRecord::Base.transaction在复杂方法中非常有效。我想知道是否可以在如下事务中从AWSS3上传/删除文件:S3Object.transactiondo#writeintofiles#raiseanexceptionend引发异常后,每个操作都应在S3上回滚。S3Object这可能吗?? 最佳答案 虽然S3API具有批量删除功能,但它不支持事务,因为每个删除操作都可以独立于其他操作成功/失败。该API不提供任何批量上传功能(通过PUT或POST),因此每个上传操作都是通过一个独立的API调用完成的

  6. ruby - Sinatra:运行 rspec 测试时记录噪音 - 2

    Sinatra新手;我正在运行一些rspec测试,但在日志中收到了一堆不需要的噪音。如何消除日志中过多的噪音?我仔细检查了环境是否设置为:test,这意味着记录器级别应设置为WARN而不是DEBUG。spec_helper:require"./app"require"sinatra"require"rspec"require"rack/test"require"database_cleaner"require"factory_girl"set:environment,:testFactoryGirl.definition_file_paths=%w{./factories./test/

  7. ruby-on-rails - Rails 5 Active Record 记录无效错误 - 2

    我有两个Rails模型,即Invoice和Invoice_details。一个Invoice_details属于Invoice,一个Invoice有多个Invoice_details。我无法使用accepts_nested_attributes_forinInvoice通过Invoice模型保存Invoice_details。我收到以下错误:(0.2ms)BEGIN(0.2ms)ROLLBACKCompleted422UnprocessableEntityin25ms(ActiveRecord:4.0ms)ActiveRecord::RecordInvalid(Validationfa

  8. ruby - 如何安全地删除文件? - 2

    在Ruby中是否有Gem或安全删除文件的方法?我想避免系统上可能不存在的外部程序。“安全删除”指的是覆盖文件内容。 最佳答案 如果您使用的是*nix,一个很好的方法是使用exec/open3/open4调用shred:`shred-fxuz#{filename}`http://www.gnu.org/s/coreutils/manual/html_node/shred-invocation.html检查这个类似的帖子:Writingafileshredderinpythonorruby?

  9. ruby-on-rails - 标准化文件名的字符串,删除重音和特殊字符 - 2

    我正在尝试找到一种方法来规范化字符串以将其作为文件名传递。到目前为止我有这个:my_string.mb_chars.normalize(:kd).gsub(/[^\x00-\x7F]/n,'').downcase.gsub(/[^a-z]/,'_')但第一个问题:-字符。我猜这个方法还有更多问题。我不控制名称,名称字符串可以有重音符、空格和特殊字符。我想删除所有这些,用相应的字母('é'=>'e')替换重音符号,并将其余的替换为'_'字符。名字是这样的:“Prélèvements-常规”“健康证”...我希望它们像一个没有空格/特殊字符的文件名:“prelevements_routin

  10. ruby-on-rails - 事件记录 : Select max of limit - 2

    我正在尝试将以下SQL查询转换为ActiveRecord,它正在融化我的大脑。deletefromtablewhereid有什么想法吗?我想做的是限制表中的行数。所以,我想删除少于最近10个条目的所有内容。编辑:通过结合以下几个答案找到了解决方案。Temperature.where('id这给我留下了最新的10个条目。 最佳答案 从您的SQL来看,您似乎想要从表中删除前10条记录。我相信到目前为止的大多数答案都会如此。这里有两个额外的选择:基于MurifoX的版本:Table.where(:id=>Table.order(:id).

随机推荐