Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 789
BozStack Avatar asked Dec 19 '22 18:12

BozStack


1 Answers

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.

like image 87
Rob Napier Avatar answered May 07 '23 13:05

Rob Napier