将NSMutableAttributedString拆分为半类

时间:2013-07-02 15:46:37

标签: ios nsrange nsmutableattributedstring

我的类别存在一些问题,将NSMutableAttributedString拆分为一半,导致NSMakeRange(...)

崩溃
#import <Foundation/Foundation.h>

@interface NSMutableAttributedString (StringSplit)
- (NSMutableAttributedString *)lastHalfLinesOfAttributedString;
@end


#import "NSAttributedString+StringSplit.h"

@implementation NSMutableAttributedString (StringSplit)

- (NSMutableAttributedString *)lastHalfLinesOfAttributedString
{
    NSLog(@"lastHalfLinesOfAttributedString with length:%d from index: %d", [self length], [self length]/2); 

    NSMutableAttributedString *result = [[NSMutableAttributedString alloc] init];
    [result insertAttributedString:[self attributedSubstringFromRange:NSMakeRange([self length]/2, [self length]-1)] atIndex:0];

    return result;
}
@end
  

lastHalfLinesOfAttributedString,长度:1020,索引:510   2013-07-02 17:43:16.209 hackers_ssh [36675:c07] *终止app到期   未被捕获的异常'NSRangeException',原因:   'NSConcreteMutableAttributedString attributionSubstringFromRange :: Out   边界'   * 首先

1 个答案:

答案 0 :(得分:1)

NSMakeRange的第二个参数代表length(从第一个参数的起始索引开始计算)。

所以你想要NSMakeRange([self length] / 2, ([self length] + 1) / 2)

顺便说一下,这种分割字符串的方法只有在字符串中没有组合字符序列或代理项对时才能正常工作。