Objective-C coding specification for iOS development

Source: Internet
Author: User
Tags constant definition

Objective-C coding specification for iOS development

Abstract: The Objective-C encoding style of each user is inconsistent, so it is difficult to maintain Code consistency and Code Review. To ensure the elegance, consistency, and ease of coding of the project code, every developer involved in the project should try to support the unified Objective-C coding style guide. The following code specifications for this project can be further optimized if there are better ones.

I,_ Language _

Use US English

II,_ Code organization _

To use # pragma mark-in function grouping and protocol/delegate classification, follow the following general structure:

 #prama mark - Lifecycle #prama mark -- (void)ViewDidLoad{}- (void)viewWillAppear:(BOOL)animated {}  #pragma mark - Custom Accessors #pragma mark -- (void)setCustomProperty:(id)value {}  - (id)customProperty {}   #pragma mark - Public #pragma mark - - (void)publicMethod {}   #pragma mark - Private #pragma mark - - (void)privateMethod {} 

III,_ Space _

Four spaces are used for indentation to ensure that the settings are set in Xcode preference settings.

Method braces and other braces (if/else/switch/while) are always inOpen the same line of statementOrOpen a new line of statementsHoweverClosing in New Line

If you prefer to open a new line of statement and close it in the new line, as shown below:

if (user.isHappy)  {    //Do something  }  else {    //Do something else  } 

IV,_ Annotation _

Note is very important, but apart from the copyright statement at the beginning, try to write the code like a document, so that others can understand the meaning of the Code directly. Do not worry that the name is too long when writing the code, trust the prompt function of Xcode.

Instance variables should be in the implementation file. m is declared or in the form of @ property in. the statement in the H file must be directly in. add @ priavte to the H file Declaration. In addition, use @ private and @ public. an indent space is required first.

Make sure that the. h file is concise as much as possible. Do not expose the API without disclosing it. Simply write it in the implementation file.

Property notes:

@ Property (nonatomic, assign) NSInteger xLineCount;/** <Number of grid crosslines */

You only need to note this. When setting its attributes, you can clearly understand the comment information corresponding to the current attribute.
If you manually write a similar format every time, you can use Xcode to customize the code module and set the current code block/* <# Description #>/

Method description:

/*! * @ Brief uses a set of data initialization columns ** @ param frame initializes frame * @ param data sets the current chart percentage ** @ return object itself */-(instancetype) initWithFrame :( CGRect) frame dictionary :( NSDictionary *) data;

Tips: There are many plug-ins that can automatically generate annotation formats. We recommend using vv1_enter

V,_ Name _

Attributes or methods declared by iOS must follow the hump naming rules.

The first letter of the class name is in upper case, the first letter of the method is in lower case, and the first letter of the parameter in the method is in lower case. Try to read the method name as a sentence to convey the meaning of the method, and do not add a prefix before the method.GetOrSet(Mixed with built-in set or get), variable names start with lowercase letters, constants start with lowercase letters k, followed by uppercase letters

When declaring a class or method, pay attention to the use of spaces. If there are too many parameters, you can keep the line feed alignment. This is also true when calling the method. parameters are written in one line or line feed with colons.

Constants should use the camper naming rules. The first letter of all words is capitalized and the prefix associated with the class name is added.

VI,_ Underline _

When using attributes, instance variables should be accessed and changed using self. This means that all attributes will have different visual effects, because they all have self ..

However, there is a special case: in the initialization method, instance variables (for example, _ variableName) should be directly used to avoid the potential side effects of getters/setters.

Local variables should not contain underscores.

VII,_ Method _

In a method signature, there should be a space after the method type (-/+. There should also be a space between each segment of the method (in line with the Apple style ). A descriptive keyword should be included before a parameter to describe the parameter.

The usage of the word "and" should be retained. It should not be used to describe multiple parameters, just like the following example of initWithWidth: height:
For example:

- (void)setExampleText:(NSString *)text image:(UIImage *)image; - (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag;- (id)viewWithTag:(NSInteger)tag;- (instancetype)initWithWidth:(CGFloat)width height:(CGFloat)height;

8,_ Variable _

Variable names should be descriptive. Variable naming for a single character should be avoided as much as possible, except in the for () loop.

Asterisk indicates that the variable is a pointer. For example,NSStringTextNeitherNSString textNeitherNSString * text _Except for constants in some special cases.

IX,_ Attribute feature _

All attribute features should be explicitly listed to help beginners read the code. The order of attribute features should be storage and atomicity, which is consistent with the Code automatically generated when the Interface Builder connects to the UI element.

@property (weak, nonatomic) IBOutlet UIView *containerView;

@property (strong, nonatomic) NSString *tutorialName;

10,_ Point Symbol syntax _

Point syntax is a convenient way to encapsulate access method calls. When you use the dot syntax, the attributes are still accessed or modified by using the getter or setter method.

Point syntax should_ Always _It is used to access and modify attributes because it makes the code more concise. [] Symbols are more inclined to be used in other examples.

XI,_ Literal value _

The literal values of NSString, NSDictionary, NSArray, and NSNumber should be used when the immutable instances of these classes are created. Note that nil values cannot be passed into NSArray and NSDictionary literal values, because this will cause crash.

Should:

NSArray *names = @[@"Brian", @"Matt", @"Chris", @"Alex", @"Steve", @"Paul"];  NSDictionary *productManagers = @{@"iPhone": @"Kate", @"iPad": @"Kamal", @"Mobile Web": @"Bill"};  NSNumber *shouldUseLiterals = @YES;  NSNumber *buildingStreetNumber = @10018;  

Should not:

NSArray *names = [NSArray arrayWithObjects:@"Brian", @"Matt", @"Chris", @"Alex", @"Steve", @"Paul", nil];  NSDictionary *productManagers = [NSDictionary dictionaryWithObjectsAndKeys: @"Kate", @"iPhone", @"Kamal", @"iPad", @"Bill", @"Mobile Web", nil]; NSNumber *shouldUseLiterals = [NSNumber numberWithBool:YES];  NSNumber *buildingStreetNumber = [NSNumber numberWithInteger:10018];

12,Constant

Constants are easy to reuse and can be quickly modified without having to search and replace them. Constants should be declared using static instead of # define unless macros are explicitly used.

Should:

static NSString * const RWTAboutViewControllerCompanyName = @"RayWenderlich.com";  static CGFloat const RWTImageThumbnailHeight = 50.0;  

Should not:

 #define CompanyName @"RayWenderlich.com"   #define thumbnailHeight 2  

XIII,Enumeration type

When using enum, we recommend that you use a new fixed basic type 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 basic type.

For example:

typedef NS_ENUM(NSInteger, RWTLeftMenuTopItemType) {    RWTLeftMenuTopItemMain,    RWTLeftMenuTopItemShows,    RWTLeftMenuTopItemSchedule  }; 

You can also assign values explicitly (display the definition of the old k-style Constant ):

typedef NS_ENUM(NSInteger, RWTGlobalConstants) {    RWTPinSizeMin = 1,    RWTPinSizeMax = 5,    RWTPinCountMin = 100,    RWTPinCountMax = 500,  }; 

The old k-style constant definition should be avoided unless the Core Foundation C code is written.

Should not:

enum GlobalConstants {    kMaxPinSize = 5,    kMaxPinCount = 500,  };  

14th,Case statement

Braces are not mandatory in case statements unless required by the compiler. When a case statement contains multiple lines of code, the braces should be added.

switch (condition) {    case 1:      // ...      break;    case 2: {      // ...      // Multi-line example using braces      break;    }    case 3:      // ...      break;    default:       // ...      break;  }  

Multiple times, one fall-through should be used when the same code is used by multiple cases. A fall-through statement is used to remove the 'Break' statement at the end of a case, so that the execution process can be redirected to the next case value. To make the code clearer, You Need To comment out a fall-through.

switch (condition) {    case 1:      // ** fall-through! **    case 2:      // code executed for values 1 and 2      break;    default:       // ...      break;  }  

'Default' is not required when the switch uses the enumeration type. For example:

RWTLeftMenuTopItemType menuType = RWTLeftMenuTopItemMain;  switch (menuType) {    case RWTLeftMenuTopItemMain:      // ...      break;    case RWTLeftMenuTopItemShows:      // ...      break;    case RWTLeftMenuTopItemSchedule:      // ...      break;  }  

15th,Private attributes

Private attributes should be declared in the class extension (anonymous classification) in the Implementation file of the class. The named classes (such as RWTPrivate or private) should never be used unless they are extended to other classes. Anonymous classification should be exposed to the test by using the naming rules of + Private. h file.

For example:

@interface RWTDetailViewController ()  @property (strong, nonatomic) GADBannerView *googleAdView;  @property (strong, nonatomic) ADBannerView *iAdView;  @property (strong, nonatomic) UIWebView *adXWebView;  @end 

16th,_ Boolean _

Objective-C uses YES and NO. Because true and false should only be used in CoreFoundation, C, or C ++ code. Since nil is parsed to NO, it is not necessary to compare in the Condition Statement. Do not compare something with YES directly, because YES is defined as 1 and a BOOL can be set to 8 bits.

This is to ensure consistency between different files and make it more concise visually.

Should:

if (someObject) {}  if (![anotherObject boolValue]) {}  

Should not:

if (someObject == nil) {}  if ([anotherObject boolValue] == NO) {}  if (isAwesome == YES) {} // Never do this.  if (isAwesome == true) {} // Never do this.  

If the name of the BOOL attribute is an adjective, the prefix "is" can be ignored for the attribute, but the common name of the get accesser must be specified. For example:

@property (assign, getter=isEditable) BOOL editable;  

17,_ Condition Statement _

The condition statement subject should be enclosed by braces to prevent errors, even if the condition statement subject can be written without braces (for example, only one line of code is used ). These errors include adding the second line of code and expecting it to be an if statement. In addition, even more dangerous defect may occur when a line of code in the if statement is commented out, then the next line of code is unconsciously part of the if statement. In addition, this style is consistent with that of other conditional statements, so it is easier to read.

Should:

if (!error) {    return success;  }  

Should not:

if (!error)    return success;  

Or

if (!error) return success;  

18,_ Ternary operator _

When it is necessary to improve the clarity and conciseness of the code, what are the three-element operators? . It is often required to evaluate a single condition. When multiple conditions are evaluated, the code is easier to read if the if statement or re-construct the instance variable. In general, it is best to use the ternary operator to assign values based on conditions.

The Non-boolean variable is compared with something. Adding parentheses () improves readability. If the variable to be compared is of the boolean type, parentheses are not required.

Should:

NSInteger value = 5;  result = (value != 0) ? x : y;  BOOL isHorizontal = YES;  result = isHorizontal ? x : y;  

Should not:

result = a > b ? x = c > d ? c : d : y;  

19th,_ Init _

The Init method should follow the naming rules of the Code Template generated by Apple. The return type should use instancetype instead of id.

- (instancetype)init {    self = [super init];    if (self) {      // ...    }    return self;  }  

20,_ Class constructor _

When a class constructor is used, it should return instancetype rather than id. This ensures that the compiler correctly infers the result type.

@interface Airplane  + (instancetype)airplaneWithType:(RWTAirplaneType)type;  @end  

21,_ CGRect function _

When accessing x, y, width, or height in CGRect, you should use the CGGeometry function instead of directly accessing it through struct. Reference Apple's CGGeometry:

All functions in this reference document accept CGRect struct as input and implicitly standardize these rectangles when calculating their results. Therefore, your application should avoid directly accessing and modifying data stored in the CGRect data structure. Instead, use these functions to manipulate rectangles and obtain their features.
Should:

CGRect frame = self.view.frame;  CGFloat x = CGRectGetMinX(frame);  CGFloat y = CGRectGetMinY(frame);  CGFloat width = CGRectGetWidth(frame);  CGFloat height = CGRectGetHeight(frame);  CGRect frame = CGRectMake(0.0, 0.0, width, height);  

Should not:

CGRect frame = self.view.frame;  CGFloat x = frame.origin.x;  CGFloat y = frame.origin.y;  CGFloat width = frame.size.width;  CGFloat height = frame.size.height;  CGRect frame = (CGRect){ .origin = CGPointZero, .size = frame.size };  

22,_ Golden path _

When conditional statement encoding is used, the code on the left hand side should be the "golden" or "happy" path. That is, do not nest the if statement. Multiple Return statements are also OK.

Should:

- (void)someMethod {    if (![someOther boolValue]) {      return;    }    //Do something important  }  

Should not:

- (void)someMethod {    if ([someOther boolValue]) {      //Do something important    }  }  

23,_ Error handling _

When a method returns an error parameter through reference, it determines the return value rather than the error variable.

Should:

NSError *error;  if (![self trySomethingWithError:&error]) {    // Handle Error  }  

Should not:

NSError *error;  [self trySomethingWithError:&error];  if (error) {    // Handle Error  }  

When the request succeeds, some Apple's APIs records the garbage values to the error parameter (if non-NULL). Then, the false negative value and crash are determined.

24,_ Singleton mode _

The singleton object should use thread-safe mode to create a shared instance.

+ (instancetype)sharedInstance {    static id sharedInstance = nil;    static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{      sharedInstance = [[self alloc] init];    });    return sharedInstance;  }  

This prevents possible and sometimes prolific crashes.

25,_ Linefeed _

Linefeed is a very important topic, because its style guide is mainly for printing and online readability.

For example:

self.productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers];  

A long line of code should be divided into two lines of code, and the next line should be separated by two spaces.

self.productsRequest = [[SKProductsRequest alloc]     initWithProductIdentifiers:productIdentifiers]; 

26,_ Xcode project _

Physical files should be synchronized with Xcode project files to avoid File expansion. Any Xcode group should be created in the file system. Code is not only grouped by type, but can also be grouped by function, so that the code is clearer.

Related Article

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.