IOS: Cocoa encoding specification-[translation] Coding Guidelines for Cocoa

Source: Internet
Author: User

 

Cocoa coding specifications-preface use public APIs to develop a Cocoa framework, plug-in, or other executable targets. The naming and coding standards in these frameworks are different from general application development. Because you developed something for developers and they are not familiar with your programming interfaces. At this time, the API naming convention will come in handy, because it makes your written interface clear and clear. This document also includes some special/important programming technologies in the development framework, such as version control, binary compatibility, error handling, and memory management. This document includes two parts: Cocoa naming rules and programming practices of some frameworks. -- The document organizes the content of this document into two major parts: The first part is the main content, which is the naming convention for programming interfaces. These specifications (with some minor exceptions) are also used by Apple to develop its own framework. These naming rules are embodied in the following aspects: "Basic code naming", "method naming", "function naming", "attribute and data type naming", and "Common abbreviations and abbreviations ". The second part discusses framework programming: "using some of the skills and techniques in the framework ".
Note: This article only translates the previous part of content, namely, Cocoa naming rules.
========================================================== = Section separation line ==================================================== ==== -- Basic naming rulesIn the face of object software library development, a problem that is often overlooked is the naming of classes, methods, functions, constants, and other programming interfaces. This chapter mainly discusses the naming rules for common codes in Cocoa interfaces.
-- General Rules -- clear

The simpler the code, the clearer the better, but the semantics cannot be ambiguous due to the conciseness:

Code Rating
InsertObject: atIndex: Good
Insert:: What is inserted? At
RemoveObjectAtIndex: Good
RemoveObject: Well, there are no questions discussed earlier.
Remove: Not clear, what is removed
Generally, do not abbreviated the object name. Even if they are long, they all work together:
Code Rating
DestinationSelection Good
DestSel Not clear
SetBackgroundColor: Good
SetBkgdColor: Not clear
-- You may think that some abbreviations are well known. However, when there is no absolute difference, especially when the developer is different from your culture and language background, looking at these abbreviations may produce ambiguity.

 

-- Of course, some common abbreviations can still be used. Refer to the General abbreviations Section

Avoid ambiguity in API naming. For example, the method name can have multiple interpretations:

Code Rating
SendPort Whether it is the sending port or the return port
DisplayName Whether to display a name or return the title of the message sender on the user interface

 

-- Consistency

Always use the name of the Cocoa programming interface. If you are not sure, check the existing header files and reference documents.

Consistency is very important when you have a class that implements polymorphism methods. The method for processing the same task in different classes should have the same name.

Code Rating
-(NSInteger) tag You must define them in the NSView, NSCell, and NSControl classes.

 

-- Do not Self-Reference names should not be Self-repeated.
Code Rating
NSString Okay
NSStringObject Self-Reference
Constants (as tags, bitwise operations can be performed) do not apply to this rule, for example, used as notification names.
Code Rating
NSUnderlineByWordMask Okay
NSTableViewColumnDidMoveNotification Okay
-- Prefix is an important part of programming interfaces. A software has different functional modules, which are usually encapsulated in a framework or similar framework. The prefix avoids naming conflicts between third-party developers and Apple. -- The prefix has a specified format. It is usually composed of 2/3 uppercase letters, rather than an underscore or a subprefix. For example, NS, IB, and AB. -- Use prefixes to name classes, protocols, functions, constants, and custom data types (typedef structures). Do not use prefixes to name methods. The method exists in the class naming area. Do not use the prefix in this area. -- For a name composed of multiple words, do not use punctuation marks (underlines, breaks, etc.) as the name part or as the separator. On the contrary, the first letter of each word is in uppercase and can be written together -- Camel Style. Note the following: -- Do not use a prefix for method names starting with lowercase letters. One exception is that the method name starts with a common abbreviation, for example, canonical representation (NSImage ).
-- Functions and constants. They use the same prefix as the related classes and use the first letter in uppercase.. For example, nsunalertpanel and NSCellDisabled. -- Avoid using underscores as prefixes. It means that the method name is Private (you can use it as an instance variable ). Apple retains this rule. However, third-party use may cause name conflicts, and they will unconsciously overwrite an existing private method. Refer to the "Private method" section. -- Class and protocol name: The name of a class should be Contains a noun that clearly indicates the role or meaning of a class (or Class Object ).. The name should have an appropriate prefix (refer to the "prefix" section ). Examples of class names in the framework are everywhere: NSString, NSDate, NSDate, NSApplication, UIApplication, NSButton, and UIButton.
The protocol name should be based on the corresponding class behavior of the Protocol. -- The methods contained in most protocols are not associated with any specific classes. This protocol should be named so that the Protocol and class cannot be confused. A common rule is: Use the dynamic term (... ing). Compare NSLocking and NSLock (looks like class name ). -- Some protocols contain unrelated methods (instead of creating multiple independent small protocols ). These protocols are closely related to a class, which mainly reflects this protocol. In this case, the naming rule is the protocol name. Same as the class name. An example is the NSObject protocol, which contains methods to query the hierarchy of any class in the parent class. Because the NSObject class implements most of the methods of the protocol, the protocol can be named by class name.
-- It is very important to name your header file. Because your name indicates the content in the class :-- Declare an independent class/protocol:If a class/protocol is not part of a file, declare it as an independent file. The file name indicates the class/protocol;
-- Declare the contact class/protocol:If there are some associated declarations (classes, protocols, and classifications), place them in a file. The file name is based on the basic classes, protocols, and classifications;
Header file Statement
NSString. h NSString and NSSMutableString
NSLock. h NSLocking protocol, NSLock, NSConditionLock, NSRecursive class
- -Header file containing the framework:All frameworks have a header file named after the framework, which contains all exposed header files in the framework. Example: Foundation. h -- Foundation. framwork. -- Add APIs for other framework classes:If the method you declare in one framework is the classification of classes in another framework, the name is "Additions" after the original class name is spliced ". An example is the NSBuddleAdditions. h header file of Applicatiion kit. -- Related functions and data types: if you have some related functions, constants, struct, and other data types, place them in the header file with the appropriate name. For example, NSGraphics. h (Applicatiion kit ). ========================================================== = Section separation line ==================================================== ====
-- Method naming methods are very common in programming interfaces. Therefore, you must pay attention to naming methods. This chapter mainly discusses the following aspects of method naming: -- when a basic rule is a method name, remember the following points: ---- The method name starts with a lower-Case name, and then the first letter of each word is capitalized (Camel-Case). Do not use the prefix;There are two exceptions. If the method uses a well-known abbreviation (for example, TIFF or PDF), you may use a prefix to define a unified private method. For details, refer to the "Private method" section. ---- If a method represents an action of an object, the method name starts with a verb;Example:-(void) invokeWithTarget :( id) target;
Do not use words such as do or does as part of the name, because these auxiliary verbs do not make any sense, and do not use them before the verb. ----- If the method returns the attributes of the message sender (object), use the attribute naming method. The word "get" is not required unless there are multiple indirect return values.See the "accessors method" section.
-(NSSize) cellSize; Correct
-(NSSize) calcCellSize; Error
-(NSSize) getCellSize; Error
---- Use keywords before all parameters
-(Void) sendAction :( SEL) aSelector toObject :( id) anObject forAllCells :( BOOL) flag; Correct
-(Void) sendAction :( SEL) aSelector :( id) anObject :( BOOL) flag; Error
---- Meaning of the word description parameter before the Parameter
-(Id) viewWithTag :( NSInteger) aTag; Correct
-(Id) taggedView :( int) aTag; Error
-----When you create a new method based on the existing method,Add a keyword to an existing Method
-(Id) initWithFrame :( CGRect) frameRect; UIView
-(Id) initWithFrame :( NSRect) frameRect mode :( int) aMode cellClass :( Class) factoryId numberOfRows :( int) rowshweigh numberOfColumns :( int) colsWide; NSMatrix, a subclass
NSView
---- Do not use and to connect Keywords of multiple parameters (Object attribute names)
-(Int) runModalForDirectory :( NSString *) path file :( NSString *) name types :( NSArray *) fileTypes; Right
-(Int) runModalForDirectory :( NSString *) path andFile :( NSString *) name andTypes :( NSArray *) fileTypes; Wrong
Although and looks good in this example, when there are many parameters in the method, it will not work if we use and again. ---- If the method contains two separate actions, use and to connect them; Example:-(BOOL) openFile :( NSString *) fullPath withApplication :( NSString *) appName andDeactivate :( BOOL) flag; -- accessors: accessors are stored in read/write object attributes. different attributes have different common formats. (Note: different formats indicate different instance variables. The accessors are in the intanceVariables and setIntanceVariables formats) ---- If an attribute represents a noun,Format: -(Type) noun;-(void) setNoun :( type) aNoun; ---- If an attribute represents an adjective,Format: -(BOOL) isAdjective;-(void) setAdjective :( BOOL) flag; (Note that the type is BOOL) For example:-(BOOL) isEditable;-(void) setEditable :( BOOL) flag; ---- if the attribute represents a verb, the format is as follows: (BOOL) verbObject;-(void) setVerbObject :( BOOL) flag; (Note that the type is BOOL)
Example:-(BOOL) showsAlpha;-(void) setShowsAlpha :( BOOL) flag; verb: current time; ---- In the name of an attribute, do not convert the verb into an adjective by word segmentation;
-(Void) setAcceptsGlyphInfo :( BOOL) flag; Right
-(BOOL) acceptsGlyphInfo; Right
-(Void) setGlyphInfoAccepted :( BOOL) flag; Wrong
-(BOOL) glyphInfoAccepted; Wrong
---- You can use modal verbs (before a verb, such as "can", "shocould", and "will") to further describe the meaning of the attribute, but do not use 'do 'or 'does '.
-(Void) setCanHide :( BOOL) flag; Y
-(BOOL) canHide; Y
-(Void) setShouldCloseDocument :( BOOL) flag; Y
-(BOOL) shouldCloseDocument; Y
-(Void) setDoesAcceptGlyphInfo :( BOOL) flag; N
-(BOOL) doesAcceptGlyphInfo; N
---- When the word "get" is used, only multiple objects/values are returned indirectly by the method.. -(Void) getLineDash :( float *) pattern count :( int *) count phase :( float *) phase; note that in this form of method, the reference parameter should be able to receive NULL, because method callers may not need multiple return values. -- The proxy method is the method called by the delegate object when a specific event occurs (if the delegate implements it), they have a specific format, these formats also apply to the object's datesource method. ---- Indicates the type of the message sending object at the beginning of the name.Example:-(BOOL) tableView :( NSTableView *) tableView shouldSelectRow :( int) row;-(BOOL) application :( NSApplication *) sender openFile :( NSString *) filename; The class name skips its prefix.And starts with lowercase. ---- If the method has only one parameter, the format is: Colon + class name (the object that calls the proxy) + sender; Example:-(BOOL) applicationOpenUntitledFile :( NSApplication *) sender ;---- One exception is that the method is used to send notifications. In this case, the method parameter is the notification object;Example:-(void) windowDidChangeScreen :( NSNotification *) notification; ----- Use did or will in the name to tell delegate that something has happened or is about to happen;Example:-(void) browserDidScroll :( NSBrowser *) sender ;---- Although you can use words such as did or will in the name to tell delegate to do something, sometimes "shocould" is more appropriate;For example:-(BOOL) windowShouldClose :( id) sender; -- Collection Method to manage the set of objects (each element called an object). The naming Method is in the following format: -(Void) addElement :( elementType) anObj;
-(Void) removeElement :( elementType) anObj;
-(NSArray *) elements;

Example:-(void) addLayoutManager :( NSLayoutManager *) obj;
-(Void) removeLayoutManager :( NSLayoutManager *) obj;
-(NSArray *) layoutManagers; The following are important and useful specifications: -- If the set has no sequence, returning NSSet is better than NSArray; -- If you insert an element in a collection, the position is very important, and the following format is better than the previous one.Example:-(void) insertLayoutManager :( NSLayoutManager *) obj atIndex :( int) index;-(void) removeLayoutManagerAtIndex :( int) index; Note the following implementation details: ---- These methods usually imply the management of ownership of the inserted object. Therefore, when adding/inserting elements, retain them and remove them when removing them;---- If the inserted object wants to keep its original held object, the setter method of the Object usually does not need retain.For example, insertLayoutManager: atIndex: method. The NSLayoutManager class is also processed in the following methods:-(void) setTextStorage :( NSTextStorage *) textStorage;-(NSTextStorage *) textStorage; Generally, you do not need to call the setTextStorage method, but you may need to rewrite it. ---- (This is hard to understand. the above is my personal opinion. Refer to the original article: If the inserted objects need to have a pointer back to the main object, you do this (typically) with a set... method that sets the back pointer but does not retain. in the case of the insertLayoutManager: atIndex: method, the NSLayoutManager class does this in these methods:-(void) setTextStorage :( NSTextStorage *) textStorage;-(NSTextStorage *) textStorage; you wocould normally not call setTextStorage: directly, but might want to override it .) the rules of the set method mentioned above are described in the NSWindow class as follows:
-(Void) addChildWindow :( NSWindow *) childWin ordered :( ns1_worderingmode) place;
-(Void) removeChildWindow :( NSWindow *) childWin;
-(NSArray *) childWindows;
-(NSWindow *) parentWindow;
-(Void) setParentWindow :( NSWindow *) window;
---- There are several basic rules for naming method parameters: ---- The parameter name is also a camel Style ---- Do not use the "pointer" or ptr words. The parameter type is more indicative of whether it is a pointer than the parameter name. ---- Avoid parameter names with one or two letters ---- Avoid abbreviations. The parameter name must contain letters. In general, the keywords in the following methods are usually matched with fixed parameters:
...action:(SEL)aSelector...alignment:(int)mode...atIndex:(int)index...content:(NSRect)aRect...doubleValue:(double)aDouble...floatValue:(float)aFloat...font:(NSFont *)fontObj...frame:(NSRect)frameRect...intValue:(int)anInt...keyEquivalent:(NSString *)charCode...length:(int)numBytes...point:(NSPoint)aPoint...stringValue:(NSString *)aString...tag:(int)anInt...target:(id)anObject...title:(NSString *)aString
---- In most cases, private method names follow the same rules as public method names. However, there is also a general rule that gives private methods a prefix, so it is easy to distinguish them from public methods.
Even if these rules are followed, private method names can still cause some special problems. When you write a subclass of the Cocoa framework class, you do not know whether your private method accidentally overwrites the private method with the same name in the method. In the Cocoa framework, naming most private methods starts with an underline prefix (for example, _ foodata) and the marking method is private. There are two suggestions for this rule: ----- Do not use the underline prefix for your own private method. Apple agreed on this rule; ----- If it is a subclass of a large cocoa framework class (such as NSView), make sure that your private method is different from that of the parent class, you can add your own unique prefix to differentiate. The prefix should be as unique as possible, perhaps based on the form of "xx _" in your company or project _". Therefore, if your project is called Byte Flogger, the prefix can be BF_addobject; Although we recommend that you use a prefix to name a private method, this seems to be in conflict with the rules mentioned earlier. However, in this case, we must ensure that the subclass inadvertently overwrites the private method of the parent class. ========================================================== = Section separation line ==================================================== ====
--- The function name in Objective-c can implement a function and method. When your object is a single instance or processing a sub-function, it is more suitable for using functions. There are several basic principles for function naming: ---- Function names are similar to method names, but there are some exceptions: they start with your prefix in the class/constant, and the first letter after the prefix is capitalized. ---- Many functions start with a verb and describe the functions implemented by the function: NSHighlightRect NSDeallocateObject---- For a function to query some attributes, the naming rules are as follows: 1. If the function returns the attribute of the first parameter, the verb is omitted.: Unsigned int NSEventMaskFromType (NSEventType type) float NSHeight (NSRect aRect) 2. If the function returns a pointer, use Get: Const char * NSGetSizeAndAlignment (const char * typePtr, unsigned int * sizep, unsigned int * alignp) 3. If the return value of a function is Boolean, the function name starts with a variable (inflected) verb.: BOOL NSDecimalIsNotANumber (const NSDecimal * decimal) ========================================================== = Section separation line ==================================================== ====
-- Attribute and data type naming: naming attributes, instance variables, constants, notifications, and exceptions. ---- Attribute and instance variable naming because of the corresponding properties of the attribute and accessor method (the get method and the part after the set are the attribute names, corresponding to the instance variables ), therefore, the name of an attribute is similar to that of an accessor method. For details, refer to the accessor method section. ---- If the attribute is name/verb, the format is: @ property (...) Type nounOrVerbExample: @ property (strong) NSString * title; @ property (assign) BOOL showsAlpha ;----- If an attribute is an adjective, the "is" prefix is omitted and the name of the accessor get method is specified.. For example: @ property (assign, getter = isEditable) BOOL editable; in many cases, when you declare an attribute, You are also sure (synthesize) the corresponding instance variable. Make sure that the instance variables briefly describe the attributes of the storage. Generally, you do not directly access the instance variables, but use the accessor method (direct access within the class, Prefix with underline; Example:
@implementation MyClass {BOOL _showsTitle;}
If you want to use an instance variable to correspond to an attribute, in @ synthesize, it is described as follows: @ implementation MyClass @ synthesize showsTitle = _ showsTitle; when adding an instance variable, there are the following rules: ----- Avoid declaring public instance variables. Developers only care about object interfaces and implementation details. Avoid declaring instance variables by declaring attributes and corresponding (synthesizing) instance variables. ----- If you need to declare instance variables, use @ private or @ protected to declare them. If the instance variable to be inherited is declared with @ protected. ----- If an instance variable is the accessible attribute of the instance, make sure that you have written the corresponding accesser method.. -- The naming rules of constant constants are closely related to how constants are generated. -- Enumeration constant

---- Use enumeration for a set of constants with values. (it does not matter if enumeration is used)
---- The names of enumeration constants and enumeration names after typedef are similar to the naming rules of functions., Refer to the function naming section. Example:

typedef enum _NSMatrixMode {NSRadioModeMatrix = 0,NSHighlightModeMatrix = 1,NSListModeMatrix = 2,NSTrackModeMatrix = 3} NSMatrixMode;
Note that _ NSMatrixMode is useless in typedef.

 

---- You can also use an untitled enumeration, suchBit mask (bit masks ),For example:

enum {NSBorderlessWindowMask = 0,NSTitledWindowMask = 1 << 0,NSClosableWindowMask = 1 << 1,NSMiniaturizableWindowMask = 1 << 2,NSResizableWindowMask = 1 << 3};

 

-- Const modifier constant

 

----- Use const to create floating point constants. You can create an integer constant. If there is no relationship between each integer constant, otherwise, use enumeration.
---- Constant naming rules modified by const, for example:Const float NSLightGray; naming rules are similar to functions. For more information, see function naming.Section.

-- Other type Constants

---- NormallyDo not use the # define pre-compilation command to create Constants. As mentioned above,Integer constants are enumerated, and floating constants are modified with const..
---- Use uppercase letters to enable the compiler to determine whether a code segment is compiled. Example: # ifdef DEBUG

---- Note that the macros defined by the compiler have two underscores (_).. Example: __mach __;

----Define string constantsFor example, for method names or dictionary keys, make sure that the compiler recognizes the string constants (compile syntax check ). Cocoa provides many String constant examples, such:APPKIT_EXTERN NSString * NSPrintCopies; The value of the string is specified as a constant (note the role of the APPKIT_EXTERN macro in Objective-C like the extern Declaration)

-- Notifications and abnormal naming rules are basically the same, but they have their own characteristics. -- Notification

If a class has a delegate, many notifications will be received by the delegate method.The names of these notifications should reflect the corresponding delegate method.. For example, a global NSApplication class object is automatically registered to receive the applicationDidBecomeActive message when the application sends the NSApplicationDidBecomeActiveNotification. Message. The notification is defined by a global String object,Format: [Name of associated class] + [Did | Will] + [UniquePartOfName] + Notification;Example:

NSApplicationDidBecomeActiveNotificationNSWindowDidMiniaturizeNotificationNSTextViewDidChangeSelectionNotificationNSColorPanelColorDidChangeNotification

 

-- Exception

 

Although you can freely use exceptions for some purposes (provided by NSException classes and related functions), Cocoa regards errors in programming, such as arrays out of bounds, as exceptions.Cocoa does not use exceptions to handle common and expected errors. For example, the returned values are nil, NULL, NO, or some error codes. For more information, see Error Handling Programming Guide.

An exception is defined by a global String object. The format is as follows:: [Prefix] + [UniquePartOfName] + Exception;The unique part of the name is a combination of words, each of which is capitalized. For example:

NSColorListIOExceptionNSColorListNotEditableExceptionNSDraggingExceptionNSFontUnavailableExceptionNSIllegalSelectorException

 

========================================================== = Section separation line ==================================================== ====

-- Common abbreviations and abbreviations

Generally, you do not need to abbreviated your name when writing an interface. Refer to the basic naming rules section. However, the abbreviations listed below are all well known and you can continue to use them. Note the following:
---- The alternative format of the abbreviation is allowed in the Standard C language library. For example, "alloc" and "getc ".

---- You can use abbreviations more freely in parameters. For example: "imageRep", "col" (for "column"), "obj", and "otherWin"
Abbreviations Meaning
Alloc Allocate
Alt Alternate
App Application, for example, NSApp global application object. "Application" is applied in the delegate method and notification medium.
Calc Calculate.
Dealloc Deallocate.
Func Function.
Horiz Horizontal.
Info Information
Init Initialize
Max/min Maximum/Minimum.
Msg Message
Nib Interface Builder archive.
Pboard Pasteboard (but only in constants
Rect Rectangle.
Rep Representation (used in class name such as NSBitmapImageRep
Temp Temporary.
Vert Vertical.
You can also use abbreviations commonly used in the computer industry, for example: ASCII, PDF, XML, HTML, URL, RTF, HTTP, TIFF, JPG, PNG, GIF, LZW, ROM, RGB, CMYK, MIDI, FTP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.