This blog post was written by Giang Vo, iOS developer. Contact him though email.
Part 1: basics on naming classes, variables, accessors, general methods and abbreviations.
Apple has laid out a set of guidelines as to how code should be written for maximum clarity and integration with the frameworks. In addition, there are some undocumented conventions that Cocoa developers often use.
In essence, the human factor present in Apple's products for the end user can be found in Objective-C and Cocoa themselves.
Putting Thought into Naming
Newer programs, though, have many more variables and functions. In this environment, a short name becomes ambiguous, which lends itself to buggy code. Xcode and other editors will autocomplete long names for you.
Cocoa strongly encourages expressive, clear, non-ambiguious names. Take a look at the classes listed in the table to the left. You have some idea of what they do just from their name.
Also notice how some are combinations of other class names. NSMenuItemCell suggests a cell which is used by a menu item.
Naming consistency isn't extra credit, it's an essential part of being a great Cocoa programmer. Remember, since you do far more reading of code than writing, invest the time to type an extra eight characters.
Class Names
Objective-C doesn't have namespaces, so prefix your class names with initials. This avoids "namespace collision," which is a situation where two pieces of code have the same name but do different things. Classes created by Cocoa Dev Central would probably be prefixed with "CDC".
If you subclass a standard Cocoa class, it's good idea to combine your prefix with the superclass name, such as CDCTableView.
Most of the standard Cocoa classes begin with NS for historical reasons, as Cocoa is based on the NeXTSTEP development framework.
Variable Names
NSString * streetAddress = @"1 Infinite Loop";
NSString * cityName = @"Cupertino";
NSString * countyName = @"Santa Clara";
As we discussed, Cocoa strongly favors clear, distinct variable names over terse ones. Ambiguity frequently results in bugs, so be explicit.
Correct
NSString * hostName;
NSNumber * ipAddress;
NSArray * accounts;
Incorrect
NSString * HST_NM; // all caps and too terse
NSNumber * theip; // a word or abbreviation?
NSMutableArray * nsma; // completely ambiguous
The variable naming syntax rules from C and many other languages apply. Variables can't start with a number, no spaces, no special characters other than underscores.
Apple discourages using an underscore as a prefix for a private instance variable.
NSString * name // correct!
NSString * _name // _incorrect_
In fact, the idea of a private prefix is largely unnecessary, as virtually all instance variables in Cocoa are protected anyway.
Variable Names: Indicating Type
Correct
NSString * accountName;
NSMutableArray * mailboxes;
NSArray * defaultHeaders;
BOOL userInputWasUpdated;
OK, But Not Ideal
NSString * accountNameString;
NSMutableArray * mailboxArray;
NSArray * defaultHeadersArray;
BOOL userInputWasUpdatedBOOL;
If a variable is not one of these types, the name should reflect it. Also, there are certain classes that you only need one instance of. In this case, just name the variable based on the class name. Font manager is a good example of this.
When to Indicate Type
NSImage * previewPaneImage; // self-explanatory
NSProgressIndicator * uploadIndicator; // shows progress for uploads
NSFontManager * fontManager; // only one of these, basic name ok
In most cases, a plural (such as mailboxes) implies an NSArray or NSSet. There's no need to say "mutable" in the name.
If a plural is not an NSArray or NSSet, it might make sense to specify this:
NSDictionary * keyedAccountNames;
NSDictionary * messageDictionary;
NSIndexSet * selectedMailboxesIndexSet;
Method Names
Example from Another Language
object.begin(resource);
object.processData(resource, data, true);
object.end(true);
While these methods names are easy to write the first time, the actual behavior is not clear. This is much more of a problem amidst massive amounts of surrounding code.
Cocoa programmers think from the end, choosing a method name based on how it will look in actual use. Let's say I want to write an in-memory file object written to disk. In some languages, that would look like this:
fileWrapper.write(path, true, true);
In Cocoa/Objective-C, it looks like this:
[fileWrapper writeToFile: path atomically: YES updateFilenames: YES];
When creating a method, ask yourself if its behavior will be clear from its name alone, particularly when surrounded by tens of thousands of lines of code.
Programmers do much more reading of code than writing, so Objective-C and Cocoa are designed to read well. Reading a message as a phrase is a good way to test your method name:
// "open the file with this application and deactivate"
[finder openFile: mailing withApplication: @"MailDrop" andDeactivate: YES];
This message is sent to NSWorkspace (aka Finder), and it clearly passes the "phrase" test.
Method Names: Accessors
Correct!
- (NSString *) name;
- (NSString *) color;
name = [object name];
color = [object color];
Incorrect
- (NSString *) getName;
- (NSColor *) getColor;
name = [object getName];
color = [object getColor];
The "get" prefix is, however, used in situations when you're returning a value indirectly via a memory address:
When to Use "Get" Prefix
// copy objects from the NSArray to the buffer
id *buffer = (id *) malloc(sizeof(id) * [array count]);
[array getObjects: buffer];
( Don't worry if you don't know what malloc does. )
The "set" prefix is always used on setters, though:
[object setName: name];
[object setColor: color];
Adjectives
For example, "selectable". In Objective-C, the getter for this key is called -isSelectable, but the setter is -setSelectable:
BOOL selectable = [textView isSelectable];
BOOL editable = [textView isEditable];
[textView setSelectable: YES]; // no "is"
[textView setEditable: YES]; // no "is"
// if textview is editable.
if ([textView isEditable])
[textView setEditable: NO];
Keep in mind that naming your accessors according to all of these rules isn't purely an issue of clarity and aesthetics. Cocoa relies heavily on key-value coding for much of its magic, and KVC relies on properly-named accessors.
Abbreviations
Here is an excerpt of the complete list of acceptable abbreviations:
int max min TIFF HTTP URL HTML PDF
rect temp info JPG FTP RTF XML ASCII
Preprocessor Contants / Macros
#define MAX_ENTRIES 20
#ifdef ENABLE_BINDINGS_SUPPORT