Domanda

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

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top