



In a nutshell: how Cocoa and Objective-C code should look Once you've figured out the basics of Objective-C and Cocoa, you're ready to start writing some code. But the conventions of naming and formatting Objective-C code are not the same as traditional C, C++ or even Java programs. 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. Part 1: basics on naming classes, variables, accessors, general methods and abbreviations.

Part 2: more detail on method names, global symbols, the id type, method parameters, etc

1 of 7 Putting Thought into Naming In the earlier days of software development, the average program was made up of far less code. With smaller functions and fewer variables, it was understood that cp meant character pointer and fread() indicated a function that read data from a file. Since space on terminal screen was limited, short names made the most sense. 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 Classes NSPasteboard

NSCell

NSComboBox

NSComboBoxCell

NSMenuItem

NSMenuItemCell

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.

2 of 7 Class Names Standard Classes NSString

NSMutableArray

NSDictionary

Custom Classes CDCRecipient

CDCEmail

CDCEmailAttachment

Custom Subclasses CDCTableView

CDCOutlineView

CDCArrayController

Whether they're a standard part of Cocoa or your own creation, class names are always capitalized. 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.

3 of 7 Variable Names Variable names start with lower-case letters, but are internally capitalized wherever a new word appears: 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.

4 of 7 Variable Names: Indicating Type In terms of real-world practice, a variable name usually does not indicate the type if it is something common like NSString, NSArray, NSNumber or BOOL. 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; Admittedly, this is a bit of a grey area.

5 of 7 Method Names Methods are perhaps the most important topic we can talk about. Most object-oriented languages use a syntax like: 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.

6 of 7 Method Names: Accessors In constrast to many other languages, Objective-C discourages use of the "get" prefix on simple accessors. Instance variables and methods can have the same name, so use this to your advantage: 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 Not all accessors return values like name, date, height, etc. Some represent a particularly quality of an object. These are often represented by BOOLs. 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.

7 of 7 Abbreviations You've probably noticed that the general principle here is to spell things out to avoid confusion. However, there are times where acronyms are so well-known that spelling them out either doesn't help or can actually create confusion. 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 Just like in ANSI C, preprocessor definitions should be in all caps #define MAX_ENTRIES 20 #ifdef ENABLE_BINDINGS_SUPPORT