NSMutableAttributedStrings - objectAtIndex:effectiveRange:: Out of bounds
Asked Answered
G

2

11

I'm trying to add some fancy text to a label, but I've run into some problems with the NSMutableAttributedString class. I was trying to achieve four this: 1. Change font, 2. Underline range, 3. Change range color, 4. Superscript range.

This code:

- (void)applicationDidFinishLaunching:(NSNotification*)aNotification
{
    NSMutableAttributedString* display = [[NSMutableAttributedString alloc]
                                          initWithString:@"Hello world!"];
    NSUInteger length = [[display string]length] - 1;

    NSRange wholeRange = NSMakeRange(0, length);
    NSRange helloRange = NSMakeRange(0, 4);
    NSRange worldRange = NSMakeRange(6, length);

    NSFont* monoSpaced = [NSFont fontWithName:@"Menlo" 
                                         size:22.0];

    [display addAttribute:NSFontAttributeName
                    value:monoSpaced
                    range:wholeRange];

    [display addAttribute:NSUnderlineStyleAttributeName 
                    value:[NSNumber numberWithInt:1] 
                    range:helloRange];

    [display addAttribute:NSForegroundColorAttributeName 
                    value:[NSColor greenColor]
                    range:helloRange];

    [display addAttribute:NSSuperscriptAttributeName 
                    value:[NSNumber numberWithInt:1] 
                    range:worldRange];

    //@synthesize textLabel; is in this file.
    [textLabel setAttributedStringValue:display];
}

Gives me this error:

NSMutableRLEArray objectAtIndex:effectiveRange:: Out of bounds

Also, I tried messing around with the ranges, but became even more confused when I tried NSRange worldRange = NSMakeRange(4, 5);. I don't understand why that produces this: Hell^o wor^ld!, where the letters inside the ^s are superscripts.

NSRange worldRange = NSMakeRange(6, 6); produces the desired effect, hello ^world!^.

What the label looks like:
outputtedText

Godgiven answered 20/7, 2012 at 2:15 Comment(0)
P
44

Your length is too long on worldRange. NSMakeRange takes two arguments, the start point and the length, not the start point and the end point. That's probably why you are getting confused about both problems.

Piliform answered 20/7, 2012 at 2:42 Comment(1)
Yes! You're right. I've been trying to use it like a substring method! Ah, rookie mistake.Godgiven
L
5

NSRange has two values, the start index and the length of the range.

So if you're starting at index 6 and going length characters after that you're going past the end of the string, what you want is:

NSRange worldRange = NSMakeRange(6, length - 6);
Lipchitz answered 20/7, 2012 at 2:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.