iOS Code specification

Source: Internet
Author: User
Tags constant definition try catch

Naming Fundamentals
    • Modeled after the Cocoa style, using a long naming style
    • The recommended naming morpheme sequence for variable naming is: The first is the namespace shorthand, then the more important, the more differentiated the morpheme the more forward. The classic structure is: scope + limit modifier + type. Cases:
UShort Apidefaultpagesize;        //OK, you can understand the meaning of ushort Apidefaultfetchpagesize;   //Add some qualification better //OK, put the Type (toolbar) back   
Name space
    • Class names, protocols, C functions, constants, structs, and enumerations should be prefixed with the namespace;
    • Class methods do not prefix, struct fields are not prefixed
View naming

For example, we assume User that there Tag are Category several model types.

The object shows a general breakdown table and a single detail, and the view controller uses modelListcontroller and modelDetailcontroller respectively, and the recommended morpheme order is: Model名 + 限定与修饰 + ListController|DetailController . To illustrate:

// OKTagUserUsedListControllerTagInCategoryListControllerCategoryDetailController// 不推荐,列表统一使用 ListController,不指明是 table view 还是 collection viewUserFollowerTableViewController// OKUserFollowerListController// 不推荐UserLikedTagListController// OK,把显示的对象放在第一位TagUserLikedListController// 糟糕,如果是 view controller,必须以 Controller 或 Displayer 结尾TagListView

Often in order to facilitate multiple interface reuse, we will unify the model display in a view controller, the other interface embedded in the view controller. We call this type of view controller that is specifically managed to display displayer . Such as:

UserListDisplayerTagListDisplayer

UIView-level components do not end with a Controller or displayer, and you can use the control end if you have administrative effects.

Motivation

The main consideration in putting the model name first (such as Taguserlikedlistcontroller rather than userlikedtaglistcontroller) is to facilitate search. Because Xcode does not support random search, the keyword can only be obtained from the trip.

If the qualifier in front, because different people understand the differences, they will also forget, this qualifier is often input can not, can only search TagList and then from the list to find, equal to the first bit of the search morpheme is discarded. When the model type is in the first place, the person who is basically familiar with the project knows what type of view to look for, the first bit is correct, and the subsequent Add/modify qualification is convenient.

Another convenient scenario is to refer to the previous interface for the implementation of another interface, the search is mostly the same type of interface, such as the implementation of Userfollowerlistcontroller reference Userfollowinglistcontroller, and the same limited scenario is relatively rare, There is less likelihood of referencing userlikedcategorylistcontroller like Userlikedtaglistcontroller.

PS: If you do not use Xcode's Open Quickly (default shortcut key Command+shift+o), it is strongly recommended that you change the habit

Method name
    • In the,,,, and alloc copy init mutableCopy new The beginning of the method to note that they will change the arc behavior. [^1]
    • get set There is a special meaning to the beginning of the method, do not define it arbitrarily.
      1. Set is the default setting method for a property, and if the function is not to set a class member, do not use the set start, which can be setup substituted.
      2. Get is independent of property methods, but in Cocoa, its standard behavior is to pass a value by reference, rather than returning the result directly. To get a variable, name the variable directly, such as: userInfomation instead of getUserInfomation .

Cases:

 //ok-(nsstring *) Name; Oops, apply the above notation-(nsstring *) Getname; OK, but rarely used-(void) GetName: (nsstring * *) Buffer range: (//ok-(nssize) cellsize; Oops, apply the above notation-(nssize) calccellsize; General settings for Controller, ok-(void) setupcontroller;void) setupcontrollerobservers; Bad, set is dedicated to setting properties-(void) Setcontroller;          
From Official document Insertobject:atindex:/    /okinsert:at:               //unclear, what was inserted? Where does the at specific refer? Removeobjectatindex:///Okremoveobject:///                 okremove:/                  /Bad, what was removed? 
Protocol Name

Good protocol name should be able to immediately tell people that this is not a class name, in addition to the usual delegate, Datesource do not end, you can also use ... ing this form, such as: NSCoding , NSCopying , NSLocking .

Notification naming

The basic naming format is: [与通知相关的类名] + [Did | Will] + [UniquePartOfName] + Notification , for example:

Nsapplicationdidbecomeactivenotificationnswindowdidminiaturizenotification  Nstextviewdidchangeselectionnotificationnscolorpanelcolordidchangenotification  
Temporary variable naming
    • Temporary variables can be written very short, such as I, K, VC such;
    • A temporary variable can use a Hungarian prefix, but the data type cannot be prefixed:
Okwcell, Vcmaster, Vtoolbar//bad, data type as prefix bool_switchstate, floatboxheight

Recommended prefixes:

prefix meaning
Ix Ordinal, starting at 0
Inch Ordinal (natural number range), starting at 1
If Type is floating-point "ordinal"
X Coordinate
Y Coordinate
W Width
H Height
Vc View Controller
V View
Constant naming

In addition to the above rule conventions, other constants contract the following prefixes:

prefix meaning
K Macro Constants
CDen Core Data Entity Name
UDk User Default Key
Apiurl Interface Address

See also: constant management

Uppercase and lowercase
    • Class name with large Hump ( UpperCamelCase )
    • Class members, methods Small Hump ( lowerCamelCase )
    • Local variable case preferred small hump, or lowercase underline ( snake_case )
    • Name of C function with big hump
Abbreviation

You can use widely used abbreviations, such as, URL JSON , and abbreviations to capitalize. But like the download shorthand for dl this is not possible.

Okid, URL, json, WWW//bad ID, URL, json, wwwdestinationselection       //Okdestsel                    // Bad SetBackgroundColor:        //Bad    
Other

I,j dedicated to cyclic marking

Name the private method do not start with "", but start with "namespace ".

Code formatting Spaces

A class method declaration has a space between the method type and the return type.

Bad-(void) MethodName: (NSString *) string;  ok-(void) MethodName: (NSString *) string;    

There should be no spaces inside the parentheses of the condition judgment.

Bad if (a < b) {    //Something}//OKif (a < b) {    //Something}

There are spaces on both sides of the relational operators (such as >= , != ) and logical operators (such as && , || ).

100)? Yes:no//OK (items): @[]

Binary arithmetic operators on both sides of the space is not determined, according to the circumstances of their own. There are no spaces before unary operators and operands.

Multiple parameter commas leave a space (this also conforms to the normal Latin syntax).

Braces

The curly brace of the method recommends another line. Method internally needs to be written in one line.

  -(void) MethodName: (NSString *) string {   ↑ space                              ↑ Space, recommended curly braces in one line      if () {   space ↑  ↑ A space, curly brace not another line      }      else {To wrap ↑↑ spaces, curly brackets do not start another line      }      }   

Motivation

The default brace position for Xcode is this: the various complements inside the method are all on the same line, the method definition is confusing, the default template is another line, but the method generated from the Interface Builder is on the same line.

Given the default behavior of Xcode, the method has a different line inside it, and the method is not strong in making a death. In addition, the template can be customized, and the code generated by the IB is not customizable, so not another line of the wording preferred.

The other line is very ugly after the code is folded.

Fold line

Unlike most other specifications, manual wrapping is not recommended.

Motivation

The effect of manual wrapping is heavily dependent on the width of the window-the window is too wide to waste valuable screen space and may not be readable when it is narrower. and Xcode automatically wrap the effect is good.

Code Organization
    • The function length (number of rows) should not exceed 2/3 screens and prohibit more than 70 rows. : Exception: For sequential execution of initialization functions, it is not necessary to limit the length if the procedure is not extracted as a standalone method.
    • The number of individual file methods should not exceed 30
    • Do not sort by category (such as putting ibaction in a piece), should be grouped together according to the task
    • Code that has more than two loops is prohibited and replaced with a function or block.

Return an error as soon as possible:

To simplify the example, there is no error handling and the use of pseudo-codeBad Example-(Task *) Creattaskwithpath: (NSString *) path {Task *atask;if ([pathIsurl]) {if ([FileManagerIswritablefileatpath:path]) {if (![ TaskManagerHastaskwithpath:path]) {atask = [[TaskAllocInitwithpath:path]; }else {ReturnNIL;} } else {return NIL;} else {return NIL;} return atask;} //rewrite example-(Task *) Creattaskwithpath: (nsstring *) path {if ( ! [Path isurl]) {return NIL;} if (![ FileManager iswritablefileatpath:path]) {return NIL;} Span class= "Pl-k" >if ([TaskManager hastaskwithpath:path]) {return NIL; } Task *atask = [[Task alloc] initwithpath:path]; return atask;}             
Class

It is forbidden to define any IVar members in the interface of the class, only the properties are allowed, but the iVar generated by the property can be used in a particular situation.

Try to always use the dot operator to access the property, not the IVar variable generated by the property. Except in the following cases:

    • Clear to avoid the modification produces the KVO notice;
    • The property getter or setter needs to be overridden;
    • Performance analysis determines that using attributes can result in unacceptable performance;
    • Multi-threaded environment, in order to prevent mutual exclusion of multiple modifications;
    • Init, the Dealloc method.

Motivation

If you use IVar, there are a lot of things that you can do that are prone to errors. Always use members, rules are simple, not easy problems.

Direct access to the IVar block will retain IVar object, which is easily ignored

Defining and using IVar generates a compilation warning, except that the default setting does not enable both warnings

Property attributes

When do I use copy?

    • The Block property is defined as copy.
    • Copy is used when an attribute is not expected to change after the value is assigned, the most common types are nsstring, Nsurl. Members of mutable types, such as Nsmutablearray, nsmutabledictionary, cannot be set to copy.

The relevant Demo can be obtained at https://github.com/BB9z/PropertyTest.

Constant

Other constants cannot be defined by a macro unless they are used to debug constants that control the behavior of different compilation modes.

Example of a constant definition:

// 头文件extern ushort APIFetchPageSizeDefault;    // 无const,可在外部修改// 实现文件ushort APIFetchPageSizeDefault = 10;
Comments

Try to make the code self-explanatory, rather than relying on annotations.

Comments should convey something that the code is not expressing or expressing. If a comment is used to explain something that should have been expressed by this code, we should consider it as a signal to change the code structure or coding conventions until the code can express itself. We rename the bad methods and the class names instead of patching them. We chose to extract some of the code snippets from the long function to form some small functions whose names could represent the intent of the original code snippet, rather than commenting on the snippets. As much as possible through the code to express. The difference between what you can express through the code and all the things you want to say will provide a reasonable candidate for comment. Comment on things that the code cannot express, rather than simply commenting on what the code does not say. "[^2]

Block annotations

Block annotations are not allowed inside the method. Unless you want to temporarily comment on a large piece of code, you should always use a line comment.

Motivation

Because block annotations are not nested correctly.

Other exceptions
    • As the maintainer of the called module, when the call is not at the time (parameter is problematic, not and timely), how to handle the need to consider (throw an exception or return an error state);
    • Do not rely on try catch, it is not a tool for you to check and fill out omissions.

iOS Code specification

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.