CFStringRef to NSString ARC leaking. Why?

2019-07-25 08:07发布

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

enter image description here

enter image description here

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?

2条回答
一纸荒年 Trace。
2楼-- · 2019-07-25 08:38

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.

查看更多
做自己的国王
3楼-- · 2019-07-25 08:48

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;
查看更多
登录 后发表回答