NSRangeException 越界错误

问题描述 投票:0回答:2
我正在设置标签的属性文本,并且收到这个奇怪的错误:由于未捕获的异常“NSRangeException”而终止应用程序,原因:“NSMutableRLEArray ReplaceObjectsInRange:withObject:length :: Out ofbounds”。我以前从未见过这个错误,所以我不知道如何修复它。这是导致崩溃的代码:

if ([cell.waveTextLabel respondsToSelector:@selector(setAttributedText:)]) { const CGFloat fontSize = 16.0f; //define attributes UIFont *boldFont = [UIFont fontWithName:@"HelveticaNeue-Medium" size:fontSize]; // Create the attributes NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:boldFont, NSFontAttributeName, nil]; NSRange rangeOfIs = [cell.cellWaveObject.waveString rangeOfString:@" is"]; NSLog(@"The range of is: {%lu, %lu}", (unsigned long)rangeOfIs.location, (unsigned long)rangeOfIs.length); NSRange nameRange = NSMakeRange(0, rangeOfIs.location); NSLog(@"The range of the name: {%lu, %lu}", (unsigned long)nameRange.location, (unsigned long)nameRange.length); NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:cell.cellWaveObject.waveString]; [attributedString setAttributes:attrs range:nameRange]; //set the label text [cell.waveTextLabel setAttributedText:attributedString]; }

我设置了一个异常断点,它在线上崩溃了

[attributedString setAttributes:attrs range:nameRange];

有人知道我该如何解决这个问题吗?

uilabel nsattributedstring nsrange nsrangeexception
2个回答
0
投票
错误明确意味着范围超出了字符串的范围,您可以尝试将您尝试应用的字符串存储在局部变量中吗? 您也可以尝试 substringWithRange 来查看您是否使用了正确的范围。 如果范围正确,则不应显示该错误。


0
投票
当您尝试使用越界索引读取或修改数组或字符串中的条目时,经常会发生“由于未捕获的异常‘NSRangeException’而终止应用程序”的问题。

在您的代码中,问题可能与设置属性的范围的计算有关。具体来说,当您计算 nameRange 时,您使用 rangeOfIs 的 location 属性作为范围的长度。如果 rangeOfIs 不包含子字符串“is”,这可能会导致越界错误,非常明显。

要解决此问题,

在尝试设置范围之前,您应该检查cell.cellWaveObject.waveString

中是否存在子字符串“is”。
此外,您还应该确保rangeOfIs.location不等于NSNotFound,表明已找到子字符串。以下是您可以修改代码来处理此问题的方法:

if ([cell.waveTextLabel respondsToSelector:@selector(setAttributedText:)]) { const CGFloat fontSize = 16.0f; UIFont *boldFont = [UIFont fontWithName:@"HelveticaNeue-Medium" size:fontSize]; NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:boldFont, NSFontAttributeName, nil]; NSRange rangeOfIs = [cell.cellWaveObject.waveString rangeOfString:@" is"]; // Check if " is" substring exists and its location is not NSNotFound if (rangeOfIs.location != NSNotFound) { NSRange nameRange = NSMakeRange(0, rangeOfIs.location); NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:cell.cellWaveObject.waveString]; [attributedString setAttributes:attrs range:nameRange]; [cell.waveTextLabel setAttributedText:attributedString]; } else { // Handle case when " is" substring is not found NSLog(@"Substring ' is' not found in wave string"); // You may want to set a default attributed text or handle it differently } }
此修改可确保您为属性设置的范围在字符串的范围内,并处理在 

cell.cellWaveObject.waveString

 中找不到子字符串“is”的情况。

© www.soinside.com 2019 - 2024. All rights reserved.