I have been looking around for the correct way to go from CFStringRef
to NSString
in ARC to avoid memory leaks and some of the main voted answers suggest:
NSString * string = (__bridge NSString *)cfString;
I am using that approach here but when profiling the app I still get a memory leak in this small method [see attached image].
So, I am not sure how to fix this. Anybody has the solution to this problem?
Thank you
So, apparently adding the CFRelease(ext)
before the return fixed the leak. Problem is I don't think I fully understand the reason. I thought that the line:
NSString * extension = (__bridge NSString*)ext
Would take ownership of the Core Foundation ext string and handle the release.
Can anybody explain what is going on here exactly?
As per the de-facto "standard" Cocoa naming convention, functions that contain Create
or Copy
in their name return an object with a reference count of 1. You have to transfer this reference count into ARC-land so that ARC can take care of it. You use the __bridge_transfer
keyword for this purpose.
NSString *string = (__bridge_transfer NSString *)cfString;
Release the ext
object or use __bridge_transfer
.
Let me explain this a bit in the way I understand it:
__bridge
– Normal casting. The retain count of casted object is partially managed by ARC and partially manually. You need to release the existing ownership on the CF
side.
__bridge_transfer
– “Converts CF
object to NS
object.” The retain count of casted object is fully managed by ARC. Existing ownership on the CF
side is disposed for you.