0

I have an ivar that is a 'plain' C array of CFURLRef structs. I call this sourceURLArray. I initialize it to hold six elements.

Later on, in a function, I create (alloc/init) an NSURL* object. I call it fileURL and I want to save a copy of that object into the first element of the aforementioned array. I thought all I needed to do was this:

        sourceURLArray[0] = (__bridge CFURLRef)([fileURL copy]);

However when I execute the code I get message sent to deallocated instance messages the second time through the function. Upon inspection of the variables, after the line above executes, sourceURLArray[0] holds the same address as fileURL. Since fileURL goes out of scope when the function completes the address in sourceURLArray[0] is deallocated.

It seems I'm misunderstanding something fundamental about either copying, nuances with toll-free bridging, or both.

3
  • Could you provide more code? Where exactly (on which line) application fails? Do you have any global/static variables involved? I'm not sure that failure is related to the line you show Commented Dec 7, 2012 at 20:06
  • Alternatively, make the ivar a C array of NSURL* and ARC should do the right thing. Commented Dec 7, 2012 at 20:24
  • Yeah, I considered that, but I have other functions already written that are expecting CFURLRefs out of this same array. Commented Dec 7, 2012 at 22:00

1 Answer 1

1

Try:

sourceURLArray[0] = (__bridge_retained CFURLRef)([fileURL copy]);

or:

sourceURLArray[0] = (CFURLRef)CFBridgingRetain([fileURL copy]);

This tells ARC that you are transferring ownership to the other array. You must now properly call CFRelease on the CFURLRef at some point.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the suggestion! When I try that the compiler complains that Cast of Obj-C pointer type id to C pointer type 'CFURLRef' cannot use __bridge_transfer. It suggests using CFBridgingRetain instead, which worked! Thanks so much for your help!
__bridge_retained equals to CFBridgingRetain, which is correct in rmaddy's answer. You just have a typo in your code with "__bridge_transfer" which equals to CFBridgingRelease.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.