iOS Development Code Specification

Source: Internet
Author: User

As a qualified coder, especially those who intend to work in the IT industry for a long time, it should be clear that the code we write is not just written to ourselves, but that the elegant coding style and good code comments are necessary for our daily development. When we write code, there is a sense that there are millions of people looking at themselves writing code, how to get them to quickly read the code they write, which requires that we always have code specification when we develop it.

    • Naming conventions
      • Constant
        • Constants should be prefixed with the name of the associated class and use the Hump naming method
// Positive Example: Static Const Homeviewcontrollerdidreceiverefreshnotification = @ "homeviewcontrollerdidreceiverefreshnotification";     //  staticconst Refresh = @ "Refresh";
      • Enumeration
        • The name of the enumeration should accurately describe the meaning of the enumeration and use the Hump naming method
        • Each value in the enumeration should begin with the defined enumeration type followed by the state, option, or type that corresponds to the enumeration value.
typedef Ns_enum (Nsinteger, afnetworkreachabilitystatus) {    =-1,    0,     1 ,     2 };
      • Notice
        • Notifications are often used to pass messages between modules, so the notification is intended to indicate as much as possible the events that occurred
        • [class name triggering notification] + [did | Would] + [action] + Notification
Nsapplicationdidbecomeactivenotificationnswindowdidminiaturizenotificationnstextviewdidchangeselectionnotificationnscolor Panelcolordidchangenotification
      • Agent
        • The type instance must be one of the parameters of the callback method
-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) Section;
        • The parameters of the callback method should contain only the class's own case, and the method name should conform to the actual meaning
-(Nsinteger) Numberofsectionsintableview: (UITableView *) TableView;
        • Start with the name of the class (the case where the callback method has more than two arguments) to indicate which class this method belongs to
-(Nsinteger) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) Indexpath;
        • Use did and will to notify Delegate of changes that have occurred or are about to occur
-(Nsindexpath *) TableView: (UITableView *) TableView Willselectrowatindexpath: (Nsindexpath *) Indexpath; -(Nsindexpath *) TableView: (UITableView *) TableView Didselectrowatindexpath: (Nsindexpath *) Indexpath;
      • Function
        • Function names typically have an abbreviated prefix that represents the frame in which the method resides
        • The words after the function prefix are displayed in hump notation with the first letter capitalized
        • The first word of a function name is a verb that represents the action performed by the method
Nshighlightrectnsdeallocateobject
        • If the function returns a property of its argument, omit the verb
int nseventmaskfromtype (nseventtype type) float Nsheight (Nsrect arect)
        • If a function returns a value through a pointer, it is necessary to facilitate the Get in the function name
Const Char *nsgetsizeandalignment (constcharintint *ALIGNP)
        • The return type of the function is named when BOOL
BOOL Nsdecimalisnotanumber (const nsdecimal *decimal)
      • Method
        • Naming should be as clear and concise as possible, features in object-c, clarity is more important than brevity, and thanks to Xcode's powerful auto-completion feature, we don't have to worry about long names.
// Clear Insertobject:atindex: // not clear, the object type of insert and the Location property of the at are not described Insert:at: // Clear Removeobjectatindex: // not clear, the object type of remove does not indicate that the function of the parameter does not specify remove:
        • Do not use shorthand words to spell out complete words.
// Clear Destinationselectionsetbackgroundcolor: // not clear, do not use shorthand Destselsetbkgdcolor:
        • If the method means that the object performs an action, use the verb to name it, take care not to use do, dose the superfluous keyword, the verb itself implies enough
// a method that starts with a verb indicates that the object performs an action -(void) Invokewithtarget: (ID) target; -(void) Selecttabviewitem: (Nstabviewitem *) Tabviewitem;
        • If the method is to get a property value for an object, name the method directly with the property name, and be careful not to add a get or other verb prefix
// correct, use the attribute name to name the method - (nssize) cellsize; // error, added superfluous verb prefix - (nssize) calccellsize; -(nssize) getcellsize;
        • You can use the word can, should, will and did to help express the meaning of the access method, but do not use do, dose
// correct -(void) setcanhide: (BOOL) flag; - (BOOL) canhide; -(void) setshouldclosedocument: (BOOL) flag; - (BOOL) shouldclosedocument; // error, do not use "do" or "does" -(void) Setdoesacceptglyphinfo: (BOOL) flag; -(BOOL) Doesacceptglyphinfo;

    • Code comments
      • Group methods using the #pragma mark-way
 #pragmaMark-private methods-(void) sampleprivatemethod{...}- (void) sampleforif{...}
- (void) sampleforwhile{...} - (void) sampleforswitch{...}- (void) wrongexamples{...}#pragmaMark-public methods-(void) Samplepublicmethodwithparam: (nsstring*) sampleparam{...}#pragmaMark-life Cycle methods-(ID) Initwithnibname: (NSString *) Nibnameornil Bundle: (NSBundle *) nibbundleornil{...}- (void) viewdidload{...}
      • Method declaration Comment
#pragma mark-?? Register interface?? ?? /* * *   Registration Interface * *  @param mobilephone registered mobile phone number *  @param areaid      phone Area ID *  @param code        Verification code *  @ param pwd         */-(Nsurlsessiondatatask *) Registerwithmobilephone: (NSString *) mobilephone                                       *)areaid    *) code                                          *) pwd                                           success: (Successblock) Success                                           Failure: (Failureblock) failure;

    • Coding style
      • Do not use the new method
        • Although many times replace the alloc init method with new , this can cause unpredictable problems with high memory, and the COCOA specification is to use the alloc init method, using the new will confuse some readers.
      • Public API to be as concise as possible
        • A common interface is designed to be concise, to meet the core functional requirements, do not design very rarely used and very complex parameters of the API, if the definition of complex methods, use categories or expand
      • Try not to access instance variables using Access methods in init and dealloc methods
        • When the init and dealloc methods are executed, the runtime environment of the class is not normal, access to variables using access methods can lead to unpredictable results, so you should directly access the instance variables within two methods
//correct, direct access to instance variables-(instancetype) init { self=[Super Init]; if(self) {_bar=[[Nsmutablestring alloc] init]; }  returnSelf ;}- (void) Dealloc {[_bar release]; [Super Dealloc];} //error, do not access by Access method-(instancetype) init { self=[Super Init]; if(self) {Self.bar= [nsmutablestringstring]; }  returnSelf ;}- (void) Dealloc {Self.bar=Nil; [Super Dealloc];}
      • Ensure that the nsstring is copied when the value is assigned
-(void) Setfoo: (NSString *= [Afoo copy];}
      • When using the x, y, width, height of a cgrect function, you should use [Cggeometry function][cggeometry-functions_1] instead of directly accessing struct members
// Positive Example: CGRect frame = self.view.frame; CGFloat x      = Cgrectgetminx (frame); CGFloat y      = cgrectgetminy (frame); CGFloat width  ==//  Counter Example:cgrect frame = self.view.frame;    CGFloat x   = frame.origin.x; CGFloat y     = frame.origin.y; CGFloat width  == frame.size.height;      
      • Nesting judgment
//Positive Example:if(!user. UserName)returnNO;if(!user. Password)returnNO;if(!user. Email)returnNO;returnYES;//Counter Example:BOOL IsValid =NO;if(user. UserName) {if(user. Password) {if(User. Email) IsValid =YES; }}returnIsValid;

iOS Development 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.