Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When I'm bridge casting an Objective C object do I have to do something special to prevent memory leaks?

I'm trying to pass an object of type id to a NSInvocation object. The compiler suggests I do a bridged cast like so:

[invocation setArgument:(__bridge void *)(argument) atIndex:idx];

Is that OK, and should I do anything else to prevent memory leaks or other problems?

like image 750
planewalker Avatar asked Mar 07 '14 15:03

planewalker


People also ask

How do you find memory leaks in Objective-C?

Diagnose the Memory Leak Expand “Open Developer Tool,” and select “Instruments” Now choose “Leaks,” and make sure you have chosen your target app and device at the top (“Choose a profiling template for…”):

What is a memory leak Objective-C?

A memory leak occurs when the system is unable to determine if allocated space in memory is in use or not. Both Swift and Objective-C use Automatic Reference Counting (ARC) to manage space in memory. ARC is a memory-management system that keeps track of how many references there are to a given object.

What is Bridge in Objective-C?

__bridge transfers a pointer between Objective-C and Core Foundation with no transfer of ownership. __bridge_retained or CFBridgingRetain casts an Objective-C pointer to a Core Foundation pointer and also transfers ownership to you.


1 Answers

__bridge will allow you (in loose terms) to go back and forth between Objective-C and C without any impact on the memory management of the object.

__bridge_transfer is for transferring an object from C to Objective-C with a change in the object's ownership. It decreases the CF retain count and hands memory management over to ARC, which should be smart enough to subsequently retain the object in the manner necessary.

__bridge_retained is essentially the inverse of __bridge_transfer, it will pass from Objective-C to C and increment the object's retain count in the process. ARC will cease to be interested in the object.

like image 200
bgfriend0 Avatar answered Nov 15 '22 09:11

bgfriend0