NSAttributedString initWithData:options:documentAttributes:error: documentAttributes not retained in ARC

StackOverflow https://stackoverflow.com/questions/21641759

  •  08-10-2022
  •  | 
  •  

Question

I'm trying to load documents from NSData (it's from a Dropbox file in my app, but for simplicity sake, the example below uses a .txt file, which causes the same issue I'm trying to fix).

Problem: I instantiate an NSDictionary, and pass it to [NSAttributedString -initWithData:options:documentAttributes:error:]as an out parameter.

However, the NSDictionary instance gets deallocated, and causes -initWithData:options:documentAttributes:error: to crash.

When I enable NSZombie, the error I get is: [__NSDictionaryI retain]: message sent to deallocated instance

-initWithData:options:documentAttributes:error: runs fine when I pass NULL to documentAttributes.

Here's the code:

NSError* error;
NSString* path = [[NSBundle mainBundle] pathForResource:@"Forward Thinking"
                                                 ofType:@"txt"];
NSData* data = [NSData dataWithContentsOfFile:path options:NSDataReadingMappedAlways error:&error];
if (data) {
    dispatch_async(dispatch_get_main_queue(), ^{
        NSDictionary* documentAttributes = [[NSDictionary alloc] init];
        NSAttributedString* attrStr = [[NSAttributedString alloc] initWithData:data options:nil documentAttributes:&documentAttributes error:NULL];
        self.textView.attributedText = attrStr;
    });
}

Any leads would be great!

Was it helpful?

Solution

You should not allocate the NSDictionary you pass to this method. What you want is:

NSDictionary* documentAttributes;
NSAttributedString* attrStr = [[NSAttributedString alloc] initWithData:data options:nil documentAttributes:&documentAttributes error:NULL];

It is passing documentAttributes to you. You don't pass the attributes to it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top