0

I am having some issues with my category for splitting an NSMutableAttributedString in half it crashes on the 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 with length:1020 from index: 510 2013-07-02 17:43:16.209 hackers_ssh[36675:c07] * Terminating app due to uncaught exception 'NSRangeException', reason: 'NSConcreteMutableAttributedString attributedSubstringFromRange:: Out of bounds' * First

David Karlsson
  • 9,396
  • 9
  • 58
  • 103

1 Answers1

1

The second argument of NSMakeRange represents the length (counted from the start index in the first argument).

So you want NSMakeRange([self length] / 2, ([self length] + 1) / 2).

By the way, this method of splitting strings only works correctly when there are no combined character sequences or surrogate pairs in the string.

Nikolai Ruhe
  • 81,520
  • 17
  • 180
  • 200
  • There is only a danger if there is such a character/pair spanning the `[self length] / 2` index. Such characters/pairs anywhere else only run the risk of the two halves not appearing to be the same length. – rmaddy Jul 02 '13 at 16:07
  • @rmaddy Yes, of course there's no harm done when not splitting a pair. Thanks, rmaddy, for making that clear. – Nikolai Ruhe Jul 02 '13 at 16:58