Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning an autorelease'd CFTypeRef with ARC

I am new to Automatic Reference Counting with LLVM and Objective-C, and have a question about returning CGImageRefs from my Objective-C function. In the days of manual reference counting, it was possible to simply cast the CGImageRef to an id, autorelease it, then return the original CGImageRef. With ARC, I am aware that you can direct the ARC system to autorelease and return your retainable object, but I do not see a way of doing this for CFTypeRefs.

Here is what I could do with ARC disabled:

- (CGImageRef)image {
    CGImageRef myImage;
    id myImageID = (id)myImage;
    [myImageID autorelease];
    return myImage;
}

So, I want to essentially create a method that, using ARC, returns a CGImageRef that is not owned by the caller. If there is a better way of doing the same thing, I am all open to ideas. I know that UIImage does something of this sort with the CGImage property.

Edit: Although disabling ARC for a specific file is a valid method of doing this, I'd prefer to use pure ARC throughout my code. This comes in handy when sharing specific code for specific files with others, since they will not need to change build settings for any given file. In order to leverage the ARC system to autorelease a CFTypeRef, you can do this:

__attribute__((ns_returns_autoreleased))
id CGImageReturnAutoreleased (CGImageRef original) {
    // CGImageRetain(original);
    return (__bridge id)original;
}

And then simply do return (__bridge CGImageRef)CGImageReturnAutoreleased(myImage) to return an autorelease'd image.

like image 985
Alex Nichol Avatar asked Oct 21 '11 22:10

Alex Nichol


1 Answers

UPDATE

As of OS X 10.9 and iOS 7.0, the public SDK includes a CFAutorelease function.

ORIGINAL

You could create a utility function like this:

void cfAutorelease(CFTypeRef *ref) {
    [[(id)ref retain] autorelease];
}

and put it in a file that you compile with ARC disabled. You need to pass the compiler flag -fno-objc-arc to disable ARC for that file. In Xcode 4, select your project, then the Build Phases tab. Open the Compile Sources section. Double-click the file that contains the utility function and put -fno-objc-arc in the popup box.

like image 105
rob mayoff Avatar answered Oct 21 '22 17:10

rob mayoff