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?

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.


You do not use bridged casting with NSInvocation.

Remember that when setting an argument on an NSInvocation you pass in a pointer to the argument, not the argument itself; casting to void* is not required. NSInvocation will know what to do with that pointer based on the method signature you used to create the NSInvocation object.

For example:

- (NSInvocation*)makeAnInvocation
{
    MyObject* anObject = [MyObject new];

    NSInvocation* inv = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(doIt:)];
    [inv setTarget:self];
    [inv setSelector:@selector(doIt:)];
    [inv setArgument:&anObject atIndex:2]; // Passing the pointer to `anObject`

    [inv retainArguments];
    return inv;
}

As far as memory management is concerned: generally speaking, if you're not invoking the method immediately then you should call the -retainArguments. This will enable the NSInvocation object to retain/copy its arguments as necessary, again based on the method signature. The arguments will then be released when the NSInvocation object is deallocated.


Need Your Help

Angular Resource object not persisting outside of Service scope in Ionic

javascript angularjs ionic-framework

In my Ionic application, using ngResource, I have my factory defined in a js/services.js file as such: