objective-c-blocksautoreleaseunsafe-unretained

dealing with autoreleased objects within dispatch_sync


What is the best solution to avoid bad access in this kind of situations ?

__block NSString* string;
dispatch_sync(dispatch_get_main_queue(), ^{
    string = [NSString stringWithString:@"I'm autoreleased!"];
});

NSLog(@"My string is: %@", string);

I changed my code to this:

NSMutableString *string = [[NSMutableString alloc] init];
dispatch_sync(dispatch_get_main_queue(), ^{
       [string appendString:@"I'm autoreleased!"];
});

NSLog(@"My string is: %@", string);
[string release];

but I was wondering if there no better solutions


Solution

  • Since you are calling release, you must be using manual reference counting. In manual reference counting, when you store something to a variable that will outlive the scope, you must retain it, and then if you will later assign something to that variable or that variable's lifetime will end, you need to release that variable first.

    So you can do this:

    __block NSString* string;
    dispatch_sync(dispatch_get_main_queue(), ^{
        string = [[NSString stringWithString:@"I'm autoreleased!"] retain];
        // or equivalently:
        // string = [[NSString alloc] initWithString:@"I'm autoreleased!"];
    });
    
    NSLog(@"My string is: %@", string);
    [string release];