0

Below code is NON ARC code, can some one tell me how can i convert it to ARC one, it has a memory leak when i am using it, to encode url.

#import "NSString+EncodeURIComponent.h"

@implementation NSString (EncodeURIComponent)

+ (NSString*)stringEncodeURIComponent:(NSString *)string {
    return [((NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                (CFStringRef)string,
                                                                NULL,
                                                                (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                                kCFStringEncodingUTF8)) autorelease];
}

@end

Thanks in advance..

4

1 回答 1

3
return CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                            (__bridge CFStringRef)string,
                                            NULL,
                                            CFSTR("!*'();:@&=+$,/?%#[]"),
                                            kCFStringEncodingUTF8));

This does the followng:

  • Remove the autorelease
  • Pass the Core Foundation object to ARC using CFBridgingRelease(). This balances the Create. In principle (though not implementation), Core Foundation performs a CFRelease() and ARC performs an objc_retain().
  • Add a _bridge case to your use of string. This tells the compiler that you are not transferring ownership between ARC and Core Foundation. You just want Core Foundation to use an ARC variable.
  • Use CFSTR() to create a constant Core Foundation string. This is more convenient than creating a constant NSString and then bridge casting it to Core Foundation.

See "Managing Toll-Free Bridging" in the Transitioning to ARC Release Notes.

于 2012-09-17T13:29:35.673 回答