Reputation: 2007
So I'm trying to change the colors of a NSMutableAttributedString but I keep getting an out of bounds exception error when I try to add multiple ranges (see below). If on the other hand I just do a single range from 0 to totalLength-1, there is no issue. I don't know why this is happening.
My code is below:
NSString *testString = @"This is my test string for this example";
NSMutableAttributedString *attribString = [[NSMutableAttributedString alloc] initWithString:testString];
int totalLength = [playerTurnString length];
[playerTurnString addAttribute:NSForegroundColorAttributeName
value:[UIColor redColor] range:NSMakeRange(0, 11)];
[playerTurnString addAttribute:NSForegroundColorAttributeName
value:[UIColor blueColor] range:NSMakeRange(12, totalLength-1)];
Upvotes: 2
Views: 623
Reputation: 119031
An NSRange
is a location and a length, so when you do
NSMakeRange(12, totalLength-1)
Your length is 12 too long and therefore exceeds the range of the string. You're trying to use it as a start and end location but that isn't how it works.
Upvotes: 3