All the specifications for programming languages, if not written here, are in Apple's documentation:
- OBJECTIVE-C programming language
- Cocoa Fundamentals Guide
- Cocoa Coding Guide
- IOS App Programming Guide
Directory
- Dot syntax
- Spacing
- Conditional judgment
- Trinocular operator
- Error handling
- Method
- Variable
- Named
- Comments
- Init and Dealloc
- Literal quantity
- CGRect function
- Constant
- Enum type
- Private properties
- Picture naming
- Boolean
- Single case
- Import
- Xcode Project
Dot syntax
You should always use point syntax to access or modify properties, and to access other instances when you prefer parentheses.
Recommended:
view.backgroundColor = [UIColor orangeColor];[UIApplication sharedApplication].delegate;
Against:
[view setBackgroundColor:[UIColor orangeColor]];UIApplication.sharedApplication.delegate;
Spacing
- One indent uses 4 spaces, or Indents with tabs (tab).
- The curly brace of the method and the other curly braces (///
if else switch while and so on) are always and declared on the same line, ending at the new line.
Recommended:
if (user.isHappy) { //Doelse { //Doelse}
- The method should be exactly an empty line, which helps with visual clarity and Code organization. The function blocks in the method should be separated by whitespace, but it is often possible to create a new method.
Conditional judgment
The conditional judgment body part should always be surrounded with braces to prevent errors, even if it can be used without curly braces (for example, it requires only one row);
These errors include adding a second line (code) and wishing it to be part of an if statement;
There is another more dangerous, when a line inside an If statement is commented out, the next line will inadvertently become part of the IF statement;
In addition, this style is more consistent with all other conditional judgments and is therefore easier to check.
Recommended:
if (!error) { return success;}
Against:
if (!error) return success;
Or
if (!errorreturn success;
Trinocular operator
Trinocular operator,? , it is only used if it can increase code clarity or neatness. A single condition should be given priority. Multi-criteria is usually easier to understand with an if statement, or to refactor to an instance variable.
Recommended:
result = a > b ? x : y;
Against:
result = a > b ? x = c > d ? c : d : y;
Error handling
When referencing a method that returns an error parameter (parameter), it should be for the return value, not the error variable.
Recommended:
NSError *error;if (![self trySomethingWithError:&error]) { // 处理错误}
Against:
NSError *error;[self trySomethingWithError:&error];if (error) { // 处理错误}
Some Apple APIs will be successful in writing some garbage values to the wrong parameters (if not null), so targeting the wrong variable can result in false results (and subsequent crashes).
Method
In the method signature, there should be a space after the-/+ symbol. There should also be a space between the method fragments.
Recommended:
- (void)setExampleText:(NSString *)text image:(UIImage *)image;
Variable
The variable name should be named as descriptive as possible. In addition for() to loops, you should avoid using single-letter variable names in other situations.
The asterisk indicates that the pointer belongs to a variable, for example: NSString *text do not write NSString* text or NSString * text
Except for constants.
Try to define attributes instead of using instance variables directly.
In addition to initialization methods ( init , initWithCoder: , etc.), dealloc methods and custom setters and getters, you should avoid direct access to instance variables.
Recommended:
@interface Model: NSObject@property(nonatomic,copy)NSString *name;@end
Against:
@interface Model : NSObject { NSString *headline;}// *号应和实例变量在一起@property(nonatomic,copy)NSString * name;@property(nonatomic,copy)NSString* name;
Variable qualifier
When it comes to the introduction of variable qualifiers in ARC,
The qualifier (,,, __strong __weak __unsafe_unretained __autoreleasing ) should be between the asterisk and the variable name, such as: NSString * __weak text .
Named
Follow Apple's naming conventions as much as possible, especially those related to memory management rules (NARC).
Long and descriptive method names and variable names are good.
Recommended:
*settingsButton;
Against:
UIButton// 不明确
Properties and local variables should use the Hump naming method and the first letter lowercase.
To be consistent, the instance variable should be named with the Hump naming method, and the first letter is lowercase and the underscore is prefixed. This is consistent with the instance variables of the LLVM auto-synthesis.
If the LLVM can automatically synthesize the variable, then let it be synthesized automatically.
Recommended:
@synthesize descriptiveVariableName = _descriptiveVariableName;
Against:
id varnm;
Comments
When needed, annotations should be used to explain why specific code does something. Any comments you use must be kept up-to-date or deleted.
Usually you should avoid a chunk of annotations, and the code should be as self-documenting as possible, with just a few lines to write a few statements. This does not apply to annotations that are used to generate documents.
Init and Dealloc
deallocThe method should be placed at the top of the implementation file and @synthesize just @dynamic behind the statement. In any class, it init should be placed directly dealloc below the method.
initThe structure of the method should look like this:
- (instancetype)init { self = [super// 或者调用指定的初始化方法 if (self) { //Custom initialization } returnself;}
Literal quantity
Each time you create,, NSString NSDictionary NSArray , and NSNumber immutable instances of a class, you should use literals. Be aware that nil values cannot be passed NSArray NSDictionary to and literal, and doing so can cause crashes.
Recommended:
NSArray *names = @[@"Marry", @"Maya", @"Vivian", @"Alex", @"Eric", @"Cherry"];NSDictionary *products = @{@"name" : @"iPhone 7", @"date" : @"2016-11-11", @"size" : @"5.5"};NSNumber *isHappyToday = @YES;NSNumber *phoneNumber = @110120119;
Against:
Nsarray*names = [Nsarrayarraywithobjects:@"Marry", @"Maya", @"Vivian", @"Alex", @"Eric", @"Cherry",Nil];nsdictionary*productmanagers = [nsdictionaryDictionarywithobjectsandkeys: @"IPhone 7", @"Name", @"2016-11-11", @"Date", @"5.5", @"Size",Nil];NSNumber*ishappytoday = [NSNumberNumberwithbool:YES];NSNumber*phonenumber = [NSNumberNumberwithinteger:10018];
CGRect function
When accessing a,,,, CGRect x y width height function should be used CGGeometry instead of directly accessing struct members. Apple's CGGeometry reference says:
All functions described in this reference that take CGRect data structures as inputs implicitly standardize those rectangles before calculating their results. For this reason, your applications should avoid directly reading and writing the data stored in the CGRect data structure. Instead, use the functions described here to manipulate rectangles and to retrieve their characteristics.
Translation: All function descriptions inside the CGRect, through the CGRect implicit data method, can be used as the input specification before the rectangle data results are calculated. For this reason, your application should avoid directly reading and writing data in CGRect. Instead, use the functions described here to manipulate rectangles and retrieve their characteristics.
Recommended:
CGRectself.view.frame;CGFloat x = CGRectGetMinX(frame);CGFloat y = CGRectGetMinY(frame);CGFloat width = CGRectGetWidth(frame);CGFloat height = CGRectGetHeight(frame);
Against:
CGRect frame = self.view.frame;x = frame.origin.x;y = frame.origin.y;CGFloat width = frame.size.width;CGFloat height = frame.size.height;
Constant
Constants prefer inline string literals or numbers, because constants can be easily reused and can be quickly changed without needing to find and replace them. Constants should be declared as static constants, not unless they are #define explicitly used as macros.
Recommended:
staticNSStringconst reusableCellIdentifier = @"Identifier";staticconstCGFloat50.0;
Against:
#define reusableCellIdentifier @"Identifier"#define cellHeight 20.0
Enum type
When used enum , it is recommended to use the new underlying type specification because of its stronger type checking and code completion capabilities. Now the SDK contains a macro to encourage the use of the new underlying type-NS_ENUM()
Recommended:
typedef NS_ENUM(NSInteger, XMButtonsType) { XMButtonsTypeAdd, XMButtonsTypeDecline};
Private properties
Private properties should be declared in the extension of the class implementation file (Extension).
Recommended:
@interface XMViewController ()@property (nonatomicNSString *privateName;@property (nonatomicassignNSInteger count;@property (nonatomicstrongNSMutableArray *dataSource;@end
Picture naming
The image name should be uniformly named to keep the organization intact. They should be named a camel string that describes their purpose, followed by an unnamed name (if any) for a custom class or attribute, and then further describe the color and/or placement, and finally their state.
Recommended:
RefreshBarButtonItem/ [email protected] and RefreshBarButtonItemSelected /[email protected]
Images in the image catalog that are used for similar purposes should be grouped into their respective groups.
Boolean
Because nil it is parsed NO , it is not necessary to compare it with the condition. Never compare directly with YES , since it YES is defined as 1 and BOOL can be as many as 8 bits.
This allows for more consistency and greater visual clarity throughout the file.
Recommended:
if{}
Against:
ifnil) {}
For BOOL This, there are two ways to use this:
if (isTrue)if (![someObject boolValue])
Against:
ifNO)ifYES// 不要这么做
If an BOOL attribute name is an adjective, the attribute can omit the "is" prefix, but specify a customary name for the get accessor, for example:
@property (assignBOOL editable;
Single case
Singleton objects should use thread-safe mode to create shared instances. (We recommend using GCD to create a singleton)
+ (instancetype)sharedInstance { staticidnil; staticdispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedInstance = [[self alloc] init]; }); return sharedInstance;}
Import
If more than one import statement is available, the statements are grouped. The comments for each grouping are optional.
// Frameworks#import <UIKit/UIKit.h>// ViewController#import "XMViewController.h"// Models#import "XMUser.h"// Views#import "XMButton.h"#import "XMUserView.h"
Xcode Project
To avoid file clutter, physical files should be kept synchronized with the Xcode project file. Any groups (group) created by Xcode must have corresponding mappings in the file system. To be clearer, the code should not only be grouped by type, but also by function.
Examples of: (by Type)
ios-Common Programming Specifications Summary