Initializing NSAttributedString Throws NSRangeException

I wrote a simple extension for decoding html objects:

extension String { func htmlDecode() -> String { if let encodedData = self.data(using: String.Encoding.unicode) { let attributedString = try! NSAttributedString(data: encodedData, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.unicode], documentAttributes: nil) return attributedString.string } return self } } 

Now it throws an error on the line if let attributedString … :

*** Application termination due to an uncaught exception "NSRangeException", reason: "*** - [__ NSArrayM objectAtIndex:]: index 4 outside the bounds [0 .. 2] '

And self not zero or something, just String , like this:

self = (String) "...ΓΌber 25'000 Franken..."

Where is this weird NSArray -exception coming from?

+9
ios swift nsattributedstring
source share
4 answers

I just run this error with another error:

*** Application termination due to the uncaught exception "NSInvalidArgumentException", reason: '- [_ SwiftValue unsignedIntegerValue]: unrecognized selector sent to instance 0x60000024b790'

And found a serious error in this piece of code:

I passed String.Encoding.unicode - the Swift value - to the Objective-C method that the application crashed. After using String.Encoding.unicode.rawValue crash disappeared:

 extension String { func htmlDecode() -> String { if let encodedData = self.data(using: String.Encoding.unicode) { if let attributedString = try? NSAttributedString(data: encodedData, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.unicode.rawValue], documentAttributes: nil) { return attributedString.string } } return self } } 
-one
source share

Shot in the dark: are you sure that the initialization takes place in the main thread?

I had exactly the same problem. I noticed that in my case the exception occurs in reproducible conditions (animations in the UICollectionViewController), but I could not find the actual reason. My best guess is a structure error, so I also suggest you create a radar.

I finished pre-rendering the HTML strings into the cache (aka array) while it was running, and then load NSAttributedStrings from it upon request.

Please note that this solution may not correspond to your use case, since I need to deal with a limited number of formatted lines at a time and, therefore, know the costs of their preliminary display.

+2
source share

It seems like an error, possibly related to how Swift strings handle characters differently than NSString .

I would put a radar.

0
source share

In my case, this was because I was trying to create an instance of NSAttributedString from a UICollectionViewCell that was in the disconnected state (before it was inserted into the parent UICollectionView).

0
source share

All Articles