I am tidying up my ancient Cocoa code to use modern naming conventions. There has been lots of discussion on best practices, but I\'m unsure of one thing.
I\'m thin
I agree with Kevin Ballard, you should prefix your category method names, particularly if you are going to distribute them to others. But you do have a valid concern the analyzer will be confused by DScopy
. The ARC compiler will similarly be confused if the definition/implementation of DScopy
is done without ARC and is used by another class using ARC (or vice versa).
My preferred solution is to use "ownership transfer annotations", such as:
NS_RETURNS_NOT_RETAINED
NS_RETURNS_RETAINED
They would be used to override the compilers default behavior of reading method names and acting on them. You might declare DScopy
like so: (This declaration must be in a header file that is imported by all the classes that use this method mentioned due to link)
-(DSManagedObject *)DScopy; NS_RETURNS_RETAINED;
Source for NS_RETURNS...
WWDC 2011 Session 322 - Objective-C Advancements in Depth. The meat of this issue begins at about time 9:10.
A note about "But I know that Apple now wants to reserve all two-character prefixes for themselves". As a personal preference I like to use the _
character to separate the prefix from the name, it works well for me. You might try something like:
-(DSManagedObject *)ds_copy; NS_RETURNS_RETAINED;
This would give you three characters, and arguably make the method name more readable.
Edit In response to link posted in comment.
However as Justin's answer to your original question says that can be broken.
With regards to attributes; I did not suggest using __attribute__((objc_method_family(copy)))
I suggested using NS_RETURNS_RETAINED
, which translates to :__attribute__((ns_returns_retained))
. While the first example there won't even compile (as he says) using - (NSString *)string __attribute__((objc_method_family(copy)));
it compiles with - (NSString *)string; NS_RETURNS_RETAINED;
just fine.
Obviously also if the NS_RETURNS_..
are "hidden" from the compiler in separate the .m
s or indirected in some other way and the compiler can't see the directives then it won't work. Because of this I would suggest putting the declaration for any methods that may cause the analyzer/compiler confusion in your main .h
file (the one that imports all the others) to limit the chances that there will be an issue.
I emailed the Apple Application Frameworks Evangelist about this, and got a reply that recommended not prefixing category method names. Which conflicts with the advice in the aforelinked WWDC10 session, but I assume reflects Apple's current thinking.
He recommended just looking at the beta seed API diffs to spot conflicts, which is what I've always been doing.