Facing crash to check special character in NSMutableAttributedString

198 views Asked by At

I have a NSString stored in cell.lblTitle.text. I am converting this NSString to NSMutableAttributedString with following code.

text = [[NSMutableAttributedString alloc] initWithData:[cell.lblTitle.text dataUsingEncoding:NSUTF8StringEncoding]
                                               options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
                                    documentAttributes:nil error:nil];

[text setAttributes:@{NSFontAttributeName:labelFont} range:NSMakeRange(0, [text length])];
[text addAttribute:NSForegroundColorAttributeName
             value:[UIColor darkGrayColor]
             range:NSMakeRange(0, [text length])];

When I print cell.lblTitle.text and its length in console then the following is my output:

po cell.lblTitle.text

Address: HM<MM-
UU@FF-
Mobile,
Alabama,
123456-
United States

po [cell.lblTitle.text length]
61

And when I print text which is my NSMutableAttributedString. The output in console is:

po text
Address: HM{
    NSColor = "UIDeviceWhiteColorSpace 0.333333 1";
    NSFont = "<UICTFont: 0x7aebc0f0> font-family: \"Futura-Medium\"; font-weight: normal; font-style: normal; font-size: 15.00pt";
}

po [text length]
11

Following is my crash log:

Terminating app due to uncaught exception 'NSRangeException', reason: 'NSMutableRLEArray objectAtIndex:effectiveRange:: Out of bounds'

So, the string after special character "<" is not identified and my app crashes. How can I manage this special character "<" so I get the output [text length] = 61.

1

There are 1 answers

0
Wain On BEST ANSWER

Your text isn't html so don't try to create it as such. Just use initWithString: to create the attributed string directly from the text.