Bad Access crash while converting to NSMutableattributed string
While doing parsing I'm converting HTML string data to attributed string text using below lines of code,
obj.strPlainText=[[NSMutableAttributedString alloc] initWithData:[obj.strContent dataUsingEncoding:NSUTF8StringEncoding]
options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute:@(NSUTF8StringEncoding)}
documentAttributes:nil
error:nil];
but my app gives bad access I'm getting an error,
[NSHTMLWebDelegate retain]: message sent to deallocated instance 0x7fa9fe027130
[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)} documentAttributes:nil error:nil];
But the app will crash if you are running it on ios 8.1,2 or 3. To avoid the crash what you can do is : run this in a queue. So that it always be on main thread.
如果你正在发布strPlainText
并且在你的项目中使用ARC,那么不需要为strPlainText
编写发布
Using this will solve your problem I think: (if it is 7.0+)
NSError* error;
NSMutableAttributedString* str = [[NSMutableAttributedString alloc] initWithData:[source dataUsingEncoding:NSUTF8StringEncoding]
options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]}
documentAttributes:nil error:&error];
You have to set str to your obj.strPlainText like obj.attributedString = str;