iOS 7中UITableView中的UITextView链接检测崩溃问题

11

我在我的UITableView中设置了一个自定义的UITableView单元格,如下所示:

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

    static NSString *identifier = @"CELL_IDENTIFIER";

    SGCustomCell *cell = (SGCustomCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) cell = [[SGCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];

    cell = [self customizedCell:cell withPost:[postsArray objectAtIndex:indexPath.row]];

    return cell;
}

我像这样设置了单元格(特别是将UITextView.text设置为nil,如此答案中所述):

descriptionLabel.text = nil;
descriptionLabel.text = post.postDescription;

descriptionLabel.frame = CGRectMake(leftMargin - 4, currentTitleLabel.frame.origin.y + currentTitleLabel.frame.size.height + 10, self.frame.size.width - topMargin * 3, 100);
[descriptionLabel sizeToFit];

这些单元格是100%可重复使用的,并且UITextView是这样初始化的(正如您所看到的,没有什么特别之处):

descriptionLabel = [[UITextView alloc] init];
descriptionLabel.font = [UIFont fontWithName:@"HelveticaNeue" size:11];
descriptionLabel.editable = NO;
descriptionLabel.scrollEnabled = NO;
descriptionLabel.dataDetectorTypes = UIDataDetectorTypeLink;
descriptionLabel.frame = CGRectMake(leftMargin, currentTitleLabel.frame.origin.y + currentTitleLabel.frame.size.height + 10, self.frame.size.width - topMargin * 3, 10);
[self addSubview:descriptionLabel];

但是当表格有约50个单元格并且我快速滚动它时,会出现以下崩溃:

Terminating app due to uncaught exception 'NSRangeException', reason: 'NSMutableRLEArray objectAtIndex:effectiveRange:: Out of bounds'

这太荒谬了 - 我将这行注释掉 - descriptionLabel.dataDetectorTypes = UIDataDetectorTypeLink; 然后应用程序停止崩溃!我花了几个小时试图找出问题所在,现在我只是得到了这个结果。

iOS 7.0.3 上测试通过


你确定这不是关于 [postsArray objectAtIndex:indexPath.row] 的问题吗? - calimarkus
当然不是!只有在打开数据检测器类型时才会发生崩溃。 - Sergey Grischyov
3个回答

5
当使用相同的单元格标识符出队两个带有数据类型的单元格时,会发生崩溃。这似乎是iOS中的一个错误,但苹果可能有很好的理由以这种方式实现它。(内存方面)
因此,唯一的100%防护措施是为包含数据类型的单元格提供唯一标识符。当然,这并不意味着您需要为表中的所有单元格设置唯一标识符,否则将占用太多内存,并且您的表滚动速度将变得非常缓慢。
您可以使用NSDataDetector来确定是否在文本中找到了匹配的类型,然后将找到的对象保存为单元格标识符,如下所示:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    NSString *row = [self.dataSource objectAtIndex:indexPath.row];
    static NSDataDetector *detector = nil;
    if (!detector)
    {
        NSError *error = NULL;
        detector = [[NSDataDetector alloc] initWithTypes:NSTextCheckingTypeLink | NSTextCheckingTypePhoneNumber error:&error];
    }

    NSTextCheckingResult *firstDataType = [detector firstMatchInString:row
                                                               options:0
                                                                 range:NSMakeRange(0, [row length])];
    NSString *dataTypeIdentifier = @"0";
    if (firstDataType)
    {
        if (firstDataType.resultType == NSTextCheckingTypeLink)
            dataTypeIdentifier = [(NSURL *)[firstDataType URL] absoluteString];
        else if (firstDataType.resultType == NSTextCheckingTypePhoneNumber)
            dataTypeIdentifier = [firstDataType phoneNumber];
    }

    NSString *CellIdentifier = [NSString stringWithFormat:@"Cell_%@", dataTypeIdentifier];

    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
...

注意:将 NSDataDetector *detector 初始化为静态变量,而不是为每个单元格初始化它,可以提高性能。

哇!非常感谢您的精彩帖子!我因为找不到解决方案,已经放弃了解决这个问题。稍后我会仔细研究您的建议,再次感谢您的回答! - Sergey Grischyov
@AmitP 你试过设置属性文本而不是普通文本吗? - Alex Sorokoletov

2
如果您使用的是iOS6或以上版本,则可以使用NSDataDetector来创建一个可归属的字符串,并将其用作TextView文本。我们将使用以下方法的修改版本。该方法接受一个字符串和一些预定义的属性(如字体和文本颜色),并且在第100个链接之后停止。然而,它对于多个电话号码存在一些问题。您需要自己定义URL转义地址的代码。NSDataDetector部分取自苹果的NSDataDetector参考文档:https://developer.apple.com/librarY/mac/documentation/Foundation/Reference/NSDataDetector_Class/Reference/Reference.html。请注意保留HTML标签。
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string attributes:attributes];
__block NSUInteger count = 0;
if (!_dataDetector)
{
    NSError *error = nil;
    _dataDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeAddress | NSTextCheckingTypePhoneNumber | NSTextCheckingTypeLink
                                                    error:&error];
}
[_dataDetector enumerateMatchesInString:string
                                options:0
                                  range:NSMakeRange(0, [string length])
                             usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){
                                 NSRange matchRange = [match range];
                                 if ([match resultType] == NSTextCheckingTypeLink)
                                 {
                                     NSURL *url = [match URL];
                                     if (url)
                                     {
                                         [attributedString addAttribute:NSLinkAttributeName value:url range:matchRange];
                                     }
                                 }
                                 else if ([match resultType] == NSTextCheckingTypePhoneNumber)
                                 {
                                     NSString *phoneNumber = [NSString stringWithFormat:@"tel:%@",[match phoneNumber]];
                                     NSURL *url = [NSURL URLWithString:phoneNumber];
                                     if (url)
                                     {
                                         [attributedString addAttribute:NSLinkAttributeName value:url range:matchRange];
                                     }
                                 }
                                 else if ([match resultType] == NSTextCheckingTypeAddress)
                                 {
                 //Warning! You must URL escape this!
                                     NSString *address = [string substringWithRange:matchRange];
                 //Warning! You must URL escape this!

                                     NSString *urlString = [NSString stringWithFormat:@"http://maps.apple.com/?q=%@",address];
                                     NSURL *url = [NSURL URLWithString:urlString];
                                     if (url)
                                     {
                                         [attributedString addAttribute:NSLinkAttributeName value:url range:matchRange];
                                     }
                                 }
                                 if (++count >= 100) *stop = YES;
                             }];
return attributedString;

2
我可以重现您的崩溃。 在TableViewCell子类中实现以下方法:
- (void)prepareForReuse
{
    [super prepareForReuse];
    [descriptionLabel setDataDetectorTypes: UIDataDetectorTypeNone];
}

在设置文本之前,请在 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 中添加以下调用:
[descriptionLabel setDataDetectorTypes: UIDataDetectorTypeLink];

对我有用。也许它取消了textview内正在进行的绘制,并以此方式避免了崩溃。

编辑:在设置文本之前调用[descriptionLabel setDataDetectorTypes: UIDataDetectorTypeNone];[descriptionLabel setDataDetectorTypes: UIDataDetectorTypeLink];似乎也可以解决崩溃问题。


1
那么这里的逻辑似乎与设置descriptionLabel.text = nil的方法相同? - Sergey Grischyov
它不能修复或防止崩溃发生 - AmitP
@AmitP 确认,它不会。 - Sergey Grischyov
1
将字段设置为UIDataDetectorTypeNone,然后立即设置为UIDataDetectorTypeLink,然后再设置“text”属性对我们有用。谢谢! - Marchy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接