0

我的类别有一些问题,将 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] * 由于未捕获的异常“NSRangeException”而终止应用程序,原因:“NSConcreteMutableAttributedString attributesSubstringFromRange:: Out of bounds” * First

4

1 回答 1

1

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

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

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

于 2013-07-02T15:58:28.287 回答