Correct connection for ARC?

I have a category class for NSString.

@implementation NSString (URLEncode) - (NSString *)URLEncodedString { __autoreleasing NSString *encodedString; NSString *originalString = (NSString *)self; encodedString = (__bridge_transfer NSString * ) CFURLCreateStringByAddingPercentEscapes(NULL, (__bridge CFStringRef)originalString, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8); return encodedString; } 

Am I using the correct bridge transfers for ARC and the new LLVM?

Source:

 - (NSString *)URLEncodedString NSString *encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)self, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8); return [encodedString autorelease]; } 
+43
objective-c automatic-ref-counting
Jul 25 2018-11-21T00:
source share
4 answers

As mentioned in the comments, I think it's nice to talk about ARC and the contents of Automatic Reference Counting here.

__autoreleasing not intended to be used in this way. It is used to pass indirect references to objects (NSError **, etc.). See 4.3.4 Switching to an output parameter by writing back .

According to 3.2.4 Bridged casts , __bridge_transfer correct, since the CFURLCreateStringByAddingPercentEscapes function returns the saved object (it has a "create" in its name). You want ARC to take responsibility for the returned object and introduce a release (or autorelease in this case) to balance this.

The __bridge for originalstring also true, you don’t want ARC to do anything special.

+43
Jul 25 '11 at 23:38
source share

This is the correct, non-penetrating version. As you say in the comments: __bridge_transfer transfer ownership of NSObject (NSString) and assume that the object is saved by the CF Framework (the CFURLCreateStringByAddingPercentEscapes method returns the retained object, so this is what we need) than on the self-object, we do not want to perform memory management. Hope helps from

 -(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding { return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (__bridge CFStringRef)self, NULL, (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ", CFStringConvertNSStringEncodingToEncoding(encoding)); } 
+28
Feb 16 '12 at 10:45
source share
 -(NSString *) urlEncoded { CFStringRef encodedCfStringRef = CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef)self,NULL,(CFStringRef)@"!*'\"();@+$,%#[]% ",kCFStringEncodingUTF8 ); NSString *endcodedString = (NSString *)CFBridgingRelease(encodedCfStringRef); return endcodedString; } 
+2
Jan 09 '13 at 8:26
source share

No __autoreleasing . The correct ARC syntax is simple:

 - (NSString *)URLEncodedString { return CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)self, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8)); } 
0
Nov 04 '14 at 12:27
source share



All Articles