Ownership regarding to returned Quartz objects

浪尽此生 提交于 2019-12-11 06:12:43

问题


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?


回答1:


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];


来源:https://stackoverflow.com/questions/2901942/ownership-regarding-to-returned-quartz-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!