iOS Development Code Specification

Source: Internet
Author: User

1.1 class name

The class name (and the category, protocol name) should be capitalized, and the word will be split in hump format.
1. Prefixes for classes
1) All class names, enumerations, structures, and protocol are best defined with a uniform identifier, either a project abbreviation, or a name abbreviation for a personal item, such as a full-capitalized XM prefix
2) According to the function module, you can add the name prefix of the function module to the class of the function module, such as the profileviewcontroller of the User Center. You can name Xmprofileviewcontroller.

suffix of class 1.2
When all protocol are defined, the suffix delegate is added. such as, Xmrefreshviewdelegate, represents the Refreshview agreement;
All controllers are added with controller, all the notification names plus notification.
Category naming
Class name + identity + extension (Uiimageview +hp+web)

//正例://反例:

1.2 Test class name
The "force" test class is named starting with the name of the class it is testing, ending with test

//正例:

1.3 Array Definitions
"Force" is part of an array type, and the array is defined as follows:

//正例:NSArray *dataSouceArr;

1.4 Method Name, parameter name, member variable, local variable
The "force" parameter name, local variables are uniformly used lowercamelcase. As far as possible is English grammar expression, avoids uses the Hanyu Pinyin to name, strictly prohibits uses the pinyin and the English mix naming way.

//正例://反例: EndKeyboardRect / shenFenZhengView

1.5 member variables
The force member variable must begin with an underscore and use lowercamelcase uniformly. As far as possible is English grammar expression, avoids uses the Hanyu Pinyin to name, strictly prohibits uses the pinyin and the English mix naming way.

//正例:_selectedMonthIndex/ _isShowResult//反例:

1.6 Method Name
"Force" should have a space after the method type (-/+ symbol). There should also be a space between the various segments of the method. Before the parameter should contain a descriptive keyword to describe the parameter, the method name unified use Lowercamelcase.

//正例: - (void)keyboardWasShown:(NSNotification*)notification;//反例: -(void)keyboardWasShown:(NSNotification//[方法类型之后未空格]

1.7 constant Naming
"Recommended" constants refer to Macros (#define), enumerations (enums), constants (const), and so on, using lowercase "k" as the prefix, followed by the Big hump nomenclature

//正例:staticNSTimeInterval20.0f;//反例: staticNSStringconst codeSuccess = @"0000"

1.8 Bundle Identifier naming
"Enforce" uses the anti-domain naming rules, all using lowercase letters. The first-level package name is COM, and the two-level package name is named according to the app.

//正例:com.elong.xman

1.9 design Pattern naming
Recommended if you use design mode, it is recommended that you show the specific pattern in the class name.
Description: The design pattern is embodied in the name, which facilitates the reader to quickly understand the architecture design idea.

//正例:@interface AIFApiProxy : NSObject@interface AIFServiceFactory : NSObject

1.10 Enumeration Class naming
The "recommended" enumeration class name and enumeration members start with XM and use Uppercamelcase, and the new fixed base type specification is recommended because it has stronger type checking and code completion
Description: Enumerations are really special constant classes, and construction methods are forced by default to be private.

//正例:typedef NS_ENUM(NSUInteger, XMRequestMethod) {    0,    XMRequestMethodPOST,    XMRequestMethodPUT,    XMRequestMethodDELETE,    XMRequestMethodHEAD,};
2. Constants, literals, enumeration definitions

2.1 constants are easy to re-use and can be quickly modified without the need to find and replace them. Constants should be declared using static instead of # define, unless the macro is explicitly used.

//正例:staticconst@"RayWenderlich.com";   //反例:#define CompanyName @"RayWenderlich.com"  

The literal values of 2.2 NSString, Nsdictionary, Nsarray, and nsnumber should be used when creating immutable instances of these classes. Please pay special attention to the nil value cannot pass in Nsarray and nsdictionary literals, because this will cause crash.

//Positive Example:Nsarray*names = @[@"Brian", @"Matt.", @"Chris", @"Alex", @"Steve", @"Paul."];nsdictionary*productmanagers = @{@"IPhone": @"Kate", @"IPad": @"Kamal", @"Mobile Web": @"Bill."};//Counter Example:Nsarray*names = [Nsarrayarraywithobjects:@"Brian", @"Matt.", @"Chris", @"Alex", @"Steve", @"Paul.",Nil];

2.3 When using enum, it is recommended to use the new fixed base type specification because it has a stronger type check and code completion. Now the SDK has a macro ns_enum () to help and encourage you to use a fixed base type.

//正例:typedef NS_ENUM(NSInteger, RWTLeftMenuTopItemType)  {       RWTLeftMenuTopItemMain,       RWTLeftMenuTopItemShows,      RWTLeftMenuTopItemSchedule   //反例:enum GlobalConstants  {       5,       500,   };  
3. OOP Protocol

3.1 Use immutable objects as much as possible
"Force" when designing a class, the property should be fully applied to encapsulate the data. In practice, it should be possible to set the externally published properties as read-only (read-only), and to publish the attributes only when it is necessary.

3.2 Communication between objects through delegates and data source Protocols
There are many ways to communicate between "coercion" objects, and the delegate mode is the most common pattern used in OC to decouple data from business logic.

3.3 Dispersing The implementation code of a class into manageable categories
The "force" class often fills in various methods, and the code of these methods is all piled into a huge implementation file, which is not working well. You can use the "classification" mechanism of OC to logically classify the class code into several partitions, which is beneficial for development and debugging.

3.4 Only release the reference and dismiss the listener in the Delloc method
"Force" essentially releases the references held by the object, and also cleans up the previously configured observation behavior.

3.5 Avoid retaining rings with weak references
The "force" retention ring causes a memory leak and is recommended to be resolved with a non-owning relationship (weak reference), where the attribute is declared as weak or assign in arc.

3.6 to automatically release the pool quickly reduce memory spikes
"Force" @autoreleasepool created this way, the object receives the Autorelease message, the system puts it in the topmost pool, can effectively reduce the memory peak.

3.7 using Dispatch_once to execute thread-safe code that runs only once
"Force" the Dispatch_once function provided by GCD simplifies the code and ensures thread safety.

+ (DataShareManager *)sharedInstance   {      static DataShareManager  nil;      staticdispatch_once_t onceToken;      dispatch_once(&onceToken, ^{          sharedManager = [[DataShareManager  alloc] init];      });      return sharedManager;  }  

3.8 provides an all-around initialization method
Provides an all-in-one initialization method in a class that should be called by other initialization methods.

3.9 Implementing the Description method
The force implementation of the description method returns a meaningful string that describes the instance.

3.10 Using a clear and coordinated naming method
The "recommended" name should be followed by a standard objective-c naming convention, so that the interface created is easier for developers to understand. The method name should be concise, read from left to right like a sentence in everyday language. The first thing to do when naming a method is to make sure that the style matches your own code or the framework that you want to integrate.
Use the iOS UI library Uikit as a column to demonstrate some of the naming conventions:
1. UIView (all views inherit from this class), the first two-letter "UI" is the generic prefix for the Uikit framework.
2. Uiviewcontroller (view class UIView) is responsible for drawing the view
3. UITableView Special view, display a series of entries in the table
4. Uitableviewdelegate this protocol defines the communication interface between the tabular view and other objects, naming the class that defines the "Delegate interface" (delegate interface), and puts it in front of the name (UITableView). The word "delegate" is added to the back, which makes it easier to read.

3.11 Prefix The private method name
"Recommended" prefixes the names of private methods so that they can be easily separated from public methods. Do not prefix the private method with an underscore, because this method is reserved for Apple.

3.12 Do not access instance variables with access methods in Init and Dealloc
"Recommended" when the Init and Dealloc methods are executed, the runtime environment of the class is not out of the normal state, and accessing variables using access methods can lead to unpredictable results, so you should directly access the instance variables within two methods.

//正例:- (instancetype)init {  self = [super init];  if (self) {    _bar = [[NSMutableString alloc] init];  }  returnself;}- (void)dealloc {  [_bar release];  [super dealloc];}

3.13 Guarantee that the NSString is copied when the value is assigned
The "recommended" nsstring, when it is passed or assigned, should be guaranteed to be a copy (copy), which prevents the NSString value from being modified by other objects without knowing it.

- (void)setFoo:(NSString *)aFoo {  _foo = [aFoo copy];}

3.14 Understanding the error model of Objective-c
Recommended you should use exceptions only if there are serious errors that can cause the entire application to crash. In the case of less serious errors, you can assign a "delegate method" to handle the error, or you can put the information error in the Nserror object and return it to the caller via an "output parameter".

3.15 Do not declare attributes in the taxonomy
"Recommended" defines all the attributes used in the encapsulated data in the main interface,
In other categories other than the Class-continuation classification, you can define access methods, but try not to define attributes.

4. Control Statements

4.1 switch block via Break/return to terminate
"Force" within a switch block, each case is either terminated by Break/return, or the comment indicates which case the program will continue to execute, and within a switch block, it must contain a default statement and put it at the end. Even if it doesn't have any code.

4.2 using curly braces in if/for/while/switch statements
The "force" conditional statement body should always be surrounded by curly braces. Although sometimes you may not use curly braces (for example, the conditional statement body has only one line of content), doing so poses a problem. For example, when you add a line of code, you may mistakenly assume that it is inside the IF statement body. Moreover, more dangerously, if the line of code after the if is commented out, the next line of code will become the code in the IF statement.

//正例:if (!error)  {         return success; }

4.3 recommended to use as little as else
"Recommended" recommended to use as few as else, the following wording:

if...return obj; } // 接着写else

Description: If you are using If-else if-else to express logic, do not exceed 3 layers and do not execute complex statements in conditional statements

4.4 objective-c Use Yes and no
"Recommended" because true and false should only be used in corefoundation,c or C + + code. Since nil resolves to no, there is no need to compare them in conditional statements. Don't compare something directly to Yes, because yes is defined as 1 and a bool can be set to 8 bits.

//正例:if (someObject) {}  if (![anotherObject boolValue]) {}  //反例:ifnil) {}  ifNO) {}  ifYES// Never do this.  iftrue// Never do this.  

4.5 ternary operator
"Recommended" When you need to improve the clarity and simplicity of the code, ternary operator?: will not be used. A single conditional evaluation often requires it. When multiple criteria are evaluated, the code is more readable if the IF statement is used or if the instance variable is re-formed. In general, it is best to use the ternary operator when assigning values based on conditions.

value5;  result = (value0) ? x : y;  BOOL isHorizontal = YES;  result = isHorizontal ? x : y;  //反例:resulta > b ? x = c > d ? c : d : y;  

4.6 Equality
"Recommended" Remember this convention when you want to achieve equality: you need to implement both the isequal and hash methods. If two objects are considered equal by isequal, their hash method needs to return the same value.

4.7 Scenarios where parameter validation is required in a method
Scenarios where parameter validation is required in the "reference" method:
1) Call the method with low frequency.
2) The execution time overhead method, the parameter check time is almost negligible, but if because the parameter error causes the intermediate execution fallback, or the error, it is not worth the candle.
3) methods that require very high stability and availability.
4) Open interface provided externally, regardless of the Dubbo/api/http interface

5. Notes

5.1 File Comments
Force
Each file must be written with a file comment, and the file comment usually contains
1. module where the file is located
2. Author information
3. Historical version Information
4. Copyright information
5. What the file contains, the role
An example of a good document comment:

afnetworking.h////Copyright (c) -Afnetworking (http://afnetworking.com/)///Permission isHereby granted, free ofCharge toAny person obtaining a copy// ofThis software andAssociated Documentation Files (the"Software"), todeal//inchThe software without restriction, including without limitation the rights// to  Use, copy, modify, merge, publish, distribute, sublicense, and/orsell//copies ofThe SOFTWARE, and  toPermit persons toWhom the software isFurnished todo so, subject toThe following conditions:////the above copyright notice andThis permission notice shall is includedinch// AllCopiesorSubstantial portions ofThe software.////the SOFTWARE isProvided" as is", without WARRANTY ofAny KIND, EXPRESSORimplied, including but notLIMITED toThe warranties ofmerchantability,//FITNESS forA particular PURPOSE andNoninfringement.inchNO EVENT shall the//AUTHORSORCOPYRIGHT Holders be liable forAny CLAIM, damagesORother//Liability, WHETHERinchAn ACTION ofContract, TORTOROTHERWISE, arising from,// out  of OR inchCONNECTION withThe softwareORThe Use OROther dealingsinchThe software.

The format of the file comments is usually not required, can be clear and easy to read, but in the entire project style to be unified.

5.2 Attribute Comments
The Force attribute comment uses the/* Comment /Document comment format.

/** 回复率*/@property (nonatomic, strong) MTPoiCompareM *replyRate;

5.3 Method Set annotations
Force
System has a self-brought method set comment code block

5.4 Code Comments
The definition of "mandatory" methods, functions, classes, protocols, and categories requires comments, and it is recommended to use Apple's standard annotation style, the advantage being that it is convenient to ALT + Click to automatically pop up comments.
There are many plugins that can automatically generate annotation formats, and we recommend using Vvdocumenter:

/** *  Get the COPY of cloud device with a given mac address. * *  @param macAddress Mac address of the device. * *  @return Instance of IPCCloudDevice. */-(IPCCloudDevice *)getCloudDeviceWithMac:(NSString *)macAddress;

5.5 protocol, delegate comments to clearly state the conditions on which they are triggered

/** Delegate - Sent when failed to init connection, like p2p failed. */- (void)initConnectionDidFailed:(IPCConnectHandler *)handler;
6. Other

6.1 Do not use the new method
"Force" although it is often possible to replace the Alloc init method with new, this can cause unpredictable problems when debugging memory. Cocoa's specification is to use the Alloc init method, and using new will confuse some readers.

6.2 #import and #include
Force
When referring to a objective-c or objective-c++ header file, use the #import
When referring to a C or C + + header file, use # include, you must ensure that the referenced file provides a protection domain (#define guard)

6.3 Thread Safety for properties
When "Force" defines a property, the compiler automatically generates a thread-safe access Method (Atomic), but this can greatly degrade performance, especially for those properties that require frequent access. So if the defined attribute does not require thread protection, remember to manually add the Property keyword nonatomic to cancel the compiler's optimizations.

6.4 using Nscache instead of nsdictionary when building a cache
The "force" Nscache can provide an elegant auto-deletion function, while the nspurgeabledata and the Nscache are used together to enable the automatic data removal function.

6.5 Simplifying the implementation code for initialize and load
"Recommended" minimize the action in the Load method. Do not wait for the lock inside, and do not invoke methods that may lock. Global constants that cannot be set by the compiler can be initialized in the Initialize method.

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.