Search code examples
objective-cquartz-graphics

Ownership regarding to returned Quartz objects


I have recently asked about autoreleasing a returned quartz object: Autorelease for CGMutablePathRef?

Dave DeLong answered my question that there is no autorelease for quartz (or any NS foundation objects) and I should use the Create Rule. However the naming convention on the document says,

The Core Foundation naming conventions, in particular use of the word “create”, only apply to C functions that return Core Foundation objects. Naming conventions for Objective-C methods are governed by the Cocoa conventions, irrespective of whether the method returns a Core Foundation or Cocoa object.

By this account since my function is a message in an objective C object it doesn't seem proper to name it createSomething. I still want to return this object. What's the best way to approach this? Should I use the Get Rule and then have the caller explicitly retain it? But this is not within Cocoa convention. What's the proper way to handle this?


Solution

  • Normally you should return an autoreleased object from an Objective-C method that returns a new object. It's easy enough to do this with Core Foundation objects. For example, take this basic class method:

    + (CFURLRef)appleWebsiteURL
    {
        CFURLRef url = CFURLCreateWithString(NULL,CFSTR("http://apple.com"),NULL);
        return (CFURLRef)[NSMakeCollectable(url) autorelease];
    }
    

    Note that the above code will work in both a garbage-collected and reference-counted environment. If you're on the iPhone, you might need to do:

    return (CFURLRef)[(NSObject*)url autorelease];