0

I have the following code snippet:

-(CFStringRef)setupFileName:(NSString*)_name :(NSString*)_extension
{
NSString* tmpName = [_name stringByAppendingString:_extension];
CFStringRef ref = (__bridge CFStringRef)tmpName;
return ref;
}

When I break at the return statement, ref contains the right data, a nice String with extension. But when I use it like this:

CFStringRef tickWav = [self setupFileName:_name :kTick];

It results in a useless character chain. Is there something corrupting my encoding, when I return the right value from the function?? What can I do?

easysaesch
  • 159
  • 1
  • 14
  • Not related to you issue, but... I'd highly recommend to name your method with all the parameters: `-(CFStringRef)setupFileName:(NSString*)_name withExtension:(NSString*)_extension` and also avoid `_` for that kind of var. Also, why is `stringByAppendingString:` call when assigning to `tmpName` between parenthesis? – Larme Jul 29 '16 at 15:35
  • It was in parenthesis because the cast to CFStringRef happend their before.. you know a solution for my problem? – easysaesch Jul 29 '16 at 15:37

1 Answers1

1

There is no automatic CFTypeRef memory management. If you were to return an NSString, it would be autoreleased. Not so for a CFStringRef. So you must do the work yourself.

You need to retain the CFStringRef with CFRetain and do a __bridge_retained cast, not a __bridge cast. You are crossing the bridge from the object world to the CFTypeRef world; you must provide memory management on this string as it crosses the bridge. You will then need to release the CFStringRef manually later on in the receiving code, or it will leak.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • But in general I would ask why you are crossing the bridge at all. Wouldn't you rather return an NSString here? – matt Jul 29 '16 at 15:41
  • Because I need a CFStringRef... but hey, __bridge_retained solved the problem for me, thank you very much. I need to investigate some more on this topic – easysaesch Jul 29 '16 at 15:43
  • Might want to read my book: http://www.apeth.com/iOSBook/ch12.html#_memory_management_of_cftyperefs – matt Jul 29 '16 at 15:49
  • Use CFStringRef exactly when you need it (and having sample code that uses CFStringRef is no reason, you can always change code). Every time you use CFStringRef you run the risk of getting it wrong. Every time you use CFStringRef in a non-trivial way the risk gets huge. Use the static analyzer which will often find errors in your code. – gnasher729 Jul 29 '16 at 19:03
  • To put it another way: may be "Because I need a CFStringRef" is true, but I find it very doubtful that you need a CFStringRef handed back to you by _this method_. If you need it for some further purpose, then _that_ is the time to cross the bridge. – matt Jul 29 '16 at 20:50