草庐IT

ios - 致命异常 : NSRangeException - index 2 beyond bounds [0 .。 1]

coder 2024-01-23 原文

在我在 swift 项目中使用的库之一中,一行导致应用程序崩溃。我试图理解并修复它,但没有运气。我知道它是由数组索引错误引起的。谁能帮忙?

崩溃报告

Fatal Exception: NSRangeException
0  CoreFoundation                 0x180a42e38 __exceptionPreprocess
1  libobjc.A.dylib                0x1800a7f80 objc_exception_throw
2  CoreFoundation                 0x180922ebc -[__NSArrayM removeObjectAtIndex:]
3                          0x10000ac70 -[ChatSectionManager messageForIndexPath:] (ChatSectionManager.m:435)
4                          0x10001c194 -[Chat tableView:cellForRowAtIndexPath:] (Chat.m:596)
5  UIKit                          0x185ee2f40 -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:]
6  UIKit                          0x185ee30a8 -[UITableView _createPreparedCellForGlobalRow:willDisplay:]

ChatSectionManager.m

 - (QBChatMessage *)messageForIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.item == NSNotFound) {
        return nil;
    }

    QMChatSection *currentSection = self.chatSections[indexPath.section];
    //crashes here line 435
    return currentSection.messages[indexPath.item];
}

Chat.m

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.chatSectionManager messagesCountForSectionAtIndex:section];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.chatSectionManager.chatSectionsCount;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *) indexPath {

    QBChatMessage *messageItem = [self.chatSectionManager messageForIndexPath:indexPath];

... 方法包含 removeObjectAtIndex

- (void)deleteMessages:(NSArray *)messages animated:(BOOL)animated {

    dispatch_async(_serialQueue, ^{

        NSMutableArray *messagesIDs = [NSMutableArray array];
        NSMutableArray *itemsIndexPaths = [NSMutableArray array];
        NSMutableIndexSet *sectionsIndexSet = [NSMutableIndexSet indexSet];

        self.editableSections = self.chatSections.mutableCopy;

        for (QBChatMessage *message in messages) {
            NSIndexPath *indexPath = [self indexPathForMessage:message];
            if (indexPath == nil) continue;

            QMChatSection *chatSection = self.chatSections[indexPath.section];
            [chatSection.messages removeObjectAtIndex:indexPath.item];

            if (chatSection.isEmpty) {
                [sectionsIndexSet addIndex:indexPath.section];
                [self.editableSections removeObjectAtIndex:indexPath.section];

                // no need to remove elements whose section will be removed
                NSArray *items = [itemsIndexPaths copy];
                for (NSIndexPath *index in items) {
                    if (index.section == indexPath.section) {
                        [itemsIndexPaths removeObject:index];
                    }
                }
            } else {

                [itemsIndexPaths addObject:indexPath];
            }
        }

        dispatch_sync(dispatch_get_main_queue(), ^{

            self.chatSections = self.editableSections.copy;
            self.editableSections = nil;

            if ([self.delegate respondsToSelector:@selector(chatSectionManager:didDeleteMessagesWithIDs:atIndexPaths:withSectionsIndexSet:animated:)]) {

                [self.delegate chatSectionManager:self didDeleteMessagesWithIDs:messagesIDs atIndexPaths:itemsIndexPaths withSectionsIndexSet:sectionsIndexSet animated:animated];
            }
        });
    });
}

注意:这个崩溃是随机发生的,我不知道为什么

织物损坏报告 http://crashes.to/s/679e90f0c90

最佳答案

肯定是deleteMessages的问题,看看你的16号线程哪里崩溃了:

QMChatSectionManager.m line 228 __48-[QMChatSectionManager deleteMessages:animated:]_block_invoke

检查第 228 行到底是哪一行可以确定问题出在哪里,但我会冒险猜测是什么

[chatSection.messages removeObjectAtIndex:indexPath.item];

所以您要在线程 16 上删除 messageForIndexPath 在主线程上引用的数据结构。正如您所注意到的,这是对竞争条件的公开邀请,几乎不可能按需重现。

解决方法是不在后台线程中修改chatSection 的内容。看起来你已经有了正确的想法,在主线程上分配完成的部分列表,

self.chatSections = self.editableSections.copy;

只需将该逻辑应用到部分列表中更改的每个项目,您的随机崩溃就会消失。

关于ios - 致命异常 : NSRangeException - index 2 beyond bounds [0 .。 1],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37150746/

有关ios - 致命异常 : NSRangeException - index 2 beyond bounds [0 .。 1]的更多相关文章

  1. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  2. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  3. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  4. ruby-on-rails - Sphinx - 何时对字段使用 'has' 和 'indexes' - 2

    我几天前在我的ruby​​onrails2.3.2上安装了Sphinx和Thinking-Sphinx,基本搜索效果很好。这意味着,没有任何条件。现在,我想用一些条件过滤搜索。我有公告模型,索引如下所示:define_indexdoindexestitle,:as=>:title,:sortable=>trueindexesdescription,:as=>:description,:sortable=>trueend也许我错了,但我注意到只有当我将:sortable=>true语法添加到这些属性时,我才能将它们用作搜索条件。否则它找不到任何东西。现在,我还在使用acts_as_tag

  5. ruby - 为什么不能使用类IO的实例方法noecho? - 2

    print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上

  6. Ruby#index 方法 VS 二进制搜索 - 2

    给定一个元素和一个数组,Ruby#index方法返回元素在数组中的位置。我使用二进制搜索实现了我自己的索引方法,期望我的方法会优于内置方法。令我惊讶的是,内置的在实验中的运行速度大约是我的三倍。有Rubyist知道原因吗? 最佳答案 内置#indexisnotabinarysearch,这只是一个简单的迭代搜索。但是,它是用C而不是Ruby实现的,因此自然可以快几个数量级。 关于Ruby#index方法VS二进制搜索,我们在StackOverflow上找到一个类似的问题:

  7. ruby - Java 8 相当于 ruby​​ each_with_index - 2

    我想知道,是否有一些流操作可以像ruby​​中的each_with_index那样做。其中each_with_index遍历值以及值的索引。 最佳答案 没有专门用于该目的的流操作。但您可以通过多种方式模仿该功能。索引变量:以下方法适用于顺序流。int[]index={0};stream.forEach(item->System.out.printf("%s%d\n",item,index[0]++));外部迭代:以下方法适用于并行流,只要原始集合支持随机访问。Listtokens=...;IntStream.range(0,toke

  8. ruby-on-rails - 致命 : Peer authentication failed for user "rails" - 2

    我正在尝试运行rakedb:create在DigitalOcean服务器上使用postgresql。但是,它返回错误Peerauthenticationfailedforuser"rails",引用config/database.yml登录凭据的存储位置奇怪的是,当我通过SSH登录服务器时,这些凭据以纯文本形式显示给我。我都试过了密码以纯文本形式显示给我,同样的事情发生了。环境在生产中,我必须手动强制执行,因为应用程序在启动时正在开发中并强制它在config/environments.rb中更改不工作。如果我不得不猜测,我可能会说环境中发生了一些有趣的事情,因为DigitalOcean

  9. ruby - 将 each_with_index 与 map 一起使用 - 2

    我想获取一个数组并将其作为订单列表。目前我正在尝试以这种方式进行:r=["a","b","c"]r.each_with_index{|w,index|puts"#{index+1}.#{w}"}.map.to_a#1.a#2.b#3.c#=>["a","b","c"]输出应该是["1.a","2.b","3.c"]。如何让正确的输出成为r数组的新值? 最佳答案 a.to_enum.with_index(1).map{|element,index|"#{index}.#{element}"}或a.map.with_index(1){|

  10. ruby - 为 IO::popen 拯救 "command not found" - 2

    当我将IO::popen与不存在的命令一起使用时,我在屏幕上打印了一条错误消息:irb>IO.popen"fakefake"#=>#irb>(irb):1:commandnotfound:fakefake有什么方法可以捕获此错误,以便我可以在脚本中进行检查? 最佳答案 是:升级到ruby​​1.9。如果您在1.9中运行它,则会引发Errno::ENOENT,您将能够拯救它。(编辑)这是在1.8中的一种hackish方式:error=IO.pipe$stderr.reopenerror[1]pipe=IO.popen'qwe'#

随机推荐