Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transfer ownership out of an @autoreleasepool with ARC

I have the following code

- (NSString *)stringByEscapingXMLEntities;
{   
    NSString *result;
    @autoreleasepool {
        result = [self stringByReplacingOccurrencesOfString:@"&" withString:@"&"];
        result = [result stringByReplacingOccurrencesOfString:@"\"" withString:@"""];
        // ... lot of -stringByReplacingOccurrencesOfString: calls
        result = [result stringByReplacingOccurrencesOfString:@" " withString:@" "];
    }
    return result;
}

I ask myself now how would I transfer ownership result out of the method. Before ARC I would have retained result before exiting the autorelease block and returned it autoreleased at the end of the method.

Thanks!

like image 341
stigi Avatar asked Feb 21 '23 19:02

stigi


1 Answers

There are two ways to do that:

  • Rename the method to something like copyStringByEscapingXMLEntities -- the copy indicates the transfer of ownership and ARC creates the code accordingly.
  • Append, in the header, NS_RETURNS_RETAINED to the method definition like this: - (NSString *)stringByEscapingXMLEntities NS_RETURNS_RETAINED.

EDIT: As 'iljawascoding' mentioned, the @autoreleasepool has no real need to be kept around -- except for optimization.


EDIT 2: And remember: ARC always does the right thing. All the things you tried (your comment) result in the very same correct program -- albeit with the lack of some optimization if result was defined as __strong.

like image 57
Max Seelemann Avatar answered Apr 07 '23 12:04

Max Seelemann