Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to manually release CFStringRef?

Can you please tell me which is the right way and why in non ARC world.

+ (NSString *)getUUID {
CFUUIDRef theUUID = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, theUUID);
CFRelease(theUUID);
return [(NSString*) string autorelease];
}

or

+ (NSString *)getUUID {
CFUUIDRef theUUID = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, theUUID);
CFRelease(theUUID);
return (NSString*)string;
}
like image 215
AAV Avatar asked Sep 21 '26 11:09

AAV


2 Answers

The other answers are correct for manual retain counting. When you come to your senses ;^) and switch to ARC, you won't be able to send autorelease. Instead, under ARC, do it this way:

+ (NSString *)getUUID {
    CFUUIDRef theUUID = CFUUIDCreate(NULL);
    CFStringRef string = CFUUIDCreateString(NULL, theUUID);
    CFRelease(theUUID);
    return CFBridgingRelease(string);
}

A CFBridgingRelease is equivalent to a CFRelease for the purposes of balancing the +1 retain count returned by CFUUIDCreateString, but also returns a still-valid reference that ARC will take care of releasing.

like image 100
rob mayoff Avatar answered Sep 23 '26 23:09

rob mayoff


CFStrings do need to be released. The first way is correct because CFString is toll-free bridged with NSString, and thus can safely be autoreleased like an NSString.

like image 34
Chuck Avatar answered Sep 23 '26 23:09

Chuck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!