This article records the Objective-C programming specification and some suggestions, which may be modified and supplemented in the future. As for the original intention, the code in the recent project I took over was “a little” messy, so I organized one. Some of them are from the Internet, and some of them are my usual code style

Method declaration and definition

A space must be used between – or + and the return type, and the parentheses must line with a space

The method should look like this:

- (void)doSomethingWithString:(NSString *)theString {
  ...
}
Copy the code

If the function name is too long, align it with a colon, like this:

- (void)doSomethingWith:(GTMFoo *)theFoo
                   rect:(NSRect)theRect
               interval:(float)theInterval {
  ...
}
Copy the code

When the first keyword is shorter than the others, make sure the next line has at least 4 Spaces of indentation, align the keywords like this:

- (void)short:(GTMFoo *)theFoo
    longKeyword:(NSRect)theRect
    evenLongerKeyword:(float)theInterval {
  ...
}
Copy the code

The method call

All arguments should be on the same line:

[myObject doFooWith:arg1 name:arg2 error:arg3];
Copy the code

Or one argument per line, aligned with a colon:

[myObject doFooWith:arg1
               name:arg2
              error:arg3];
Copy the code

Method definitions, like method declarations, indent the next line with four Spaces when the keyword is not long enough to align with a colon

[myObj short:arg1
    longKeyword:arg2
    evenLongerKeyword:arg3];
Copy the code

Do not use the indentation style:

[myObject doFooWith:arg1 name:arg2  // some lines with >1 arg
              error:arg3];

[myObject doFooWith:arg1
               name:arg2 error:arg3];

[myObject doFooWith:arg1
          name:arg2  // aligning keywords instead of colons
          error:arg3];
Copy the code

named

Naming conventions are important for maintainable code. Objective-c method names tend to be quite long, but blocks of code read like prose and don’t require much code comment

We basically abide by standard Objective-C naming rules when writing pure Objective-C code,

The file name

extension Document classification
.h C/C++/Objective-C headers
.m Objective-c implementation file
.mm Ojbective-C++ implementation file
.cc Pure C++ implementation file
.c Pure C implementation file

The name of the class

Class names (as well as category and protocol names) should begin with a capital letter and split words in a camel camel format

Objective – C method name

The method name should begin with a lowercase letter and be mixed with a camel’s back. Each named parameter should also start with a lowercase letter. Method names should read as much as possible like sentences, which means you should choose parameter names that read smoothly with the method name. (for example, convertPoint: fromRect: or replaceCharactersInRange: withString:). See Apple’s Guide to Naming Methods for details.

  • Correct:- (instancetype)initWithWidth:(float)width :(float)height;
  • Bad:- (id)initWithWidth:(float)width andHeight:(float)height;

The variable name

You should use the hump nomenclature, and the variable name should be able to represent its own meaning as far as possible. Try to avoid mixed naming in Chinese and English. It is recommended to use the ‘_’ underscore to separate Chinese and English. Avoid naming things like this

NSDictionary *d0 = [ACGPCacheCenter readFileAtSubDir: HSHomePageSubDirForAD];
NSDictionary *d2 = [ACGPCacheCenter readFileAtSubDir: HSHomePageSubDirForZX];
NSDictionary *d3 = [ACGPCacheCenter readFileAtSubDir: HSHPSubDirForEntry];
NSDictionary *d4 = [ACGPCacheCenter readFileAtSubDir: HSHPSubDirForCopywriting];
Copy the code

Loop and some very short lifetime, very easy to understand variables can be free to use simple single letter and so on variable names

Constant names

Constant names (such as macro definitions, enumerations, static local variables, etc.) should start with a lowercase k and use a hump to separate words (e.g., kInvalidHandle, kWritePerm)


annotation

It is recommended not to comment too much and try to make the code self-explanatory. Rather than giving obscure names to types and variables and then writing comments about them, give them meaningful names

Here are some suggestions for comments:

H File comments

A.h file with a VVDocumenter comment before interface, such as this class, whose name doesn’t know which module does what.

@interface HSHPCopywritingCell : HSBaseCollectionViewCell

@end
Copy the code

Should be changed to

/** home module - Select stock cell */
@interface HSHPCopywritingCell : HSBaseCollectionViewCell

@end
Copy the code

When you encounter the class in the business code, hold down the Alt button and click on the class name to see the Description of the class as follows:

Attribute and member variable annotations

Comments for attributes, member variables, and enumerated types are recommended to be commented with ///<

@property (nonatomic.strong) HSMarketIndexModel *USmodel;      ///< US stock index model
@property (nonatomic.strong) HSMarketIndexModel *HKmodel;      ///< Hong Kong stock index model
@property (nonatomic.strong) HSMarketIndexView *indexView;     / / / < index view
Copy the code

You can also view the Description of the class by holding down the Alt button and clicking on the class name. You can also view the Description of the class by annotating /** U.S. Stock Index */, but too many attributes may not be beautiful

Code block comment

Use #pragma mark to sort code, #pragma mark does not underline, #pragma mark – does underline

A similar block of code is recommended:

#pragma mark - ================ LifeCycle =================
- (void)viewDidLoad {
    [selfconfigUI]; . } - (void) viewWillAppear:(BOOL)animated {
}...

- (void)configUI {
}

#pragma mark - ================ Public Methods =================

#pragma mark ==== Core exposes method annotations
- (void)somePublicMethod {
}

#pragma mark ==== Core expose method annotation 2
- (void)somePublicMethod2 {
}

#pragma mark - ================ Private Methods =================

#pragma mark ==== Core private method comments
- (void)somePrivateMethod {
}

#pragma mark - ================ UITableView Delegate =================

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
}...

#pragma mark - ================ Actions =================

- (void)someButtonClicked {
}

#pragma mark - ================ Getter and Setter =================

- (void)setModelArray:(NSMutableArray *)modelArray {
}

Copy the code

** Note: The ** code blocks should be sorted from important to unimportant, with unimportant blocks such as getters coming last. Make sure that the useful code is the first thing that pops up when someone opens your class


other

Keep the public API simple

If a function doesn’t need to be exposed at all, don’t do it, same with properties, and annotate methods reasonably VVDocumenter, expose properties and constants and enumerations with ///< whenever possible, unless it’s really, really simple and can be omitted

About the warning

Some of them may be type-conversion warnings, some may be useless variables, the code will never be executed, obsolete methods, etc. It’s a good thing to be a little squeaky-clean and strict with your code

About obsolete code

If you encounter discarded code, classes that are not used (header files) and commented out code in the project, you should try to delete them unless you must retain them. If you retain them, you are advised to use TODO annotations, and the reasons for preserving them as well as the relevant responsible people, so that others will not be overwhelmed


Some advice

When defining constants: use type constants more often than #define preprocessors

The macro definition has no type and is at risk of being repeatedly defined, affecting project compilation speed. Suggest using

static NSString * const kConst = @"Hello";static const CGFloat kWidth = 10.0;
Copy the code

Instead of:

#define kConst @"Hello"
# define kWidth 10.0
Copy the code

When defining publicly available constants, we generally use the following definition

//Test.h
extern NSString * const kClassNameconst;
//Test.m
NSString * const kClassNameconst = @"hello";
Copy the code

About the enumeration

NS_ENUM and NS_OPTIONS are recommended

typedef NS_ENUM(NSInteger,TestEnum) {
    MY_INT_CONST = 12345
};

typedef NS_OPTIONS(NSInteger, SelectType) {
    SelectA    = 0,
    SelectB    = 1 << 0,
    SelectC    = 1 << 1,
    SelectD    = 1 << 2
};
Copy the code

One advantage of not implementing the default branch in switch statements of enumerated types is that when we add members to an enumeration, the compiler will tell the developer that the switch statement does not handle all enumerations

Use concise literal syntax whenever possible

NSArray *animals = @[@"dog".@"pig".@"you"];
Dictionary *dict = @{@"animal":@"tiger".@"phone":@"iPhone 6"};

NSString *dog = animals[0];
NSString *iphone = dict[@"phone"];

Copy the code

Property strong, copy

Do not use the copy modifier when defining mutable types, which can cause crashes

@property (nonatomic.copy) NSMutableArray *mutableArrayOfCopy;   ///< Crashes when data is inserted
Copy the code

Copy is recommended for immutable types like NSString and NSArray, and strong is fine, but to determine if the situation really needs strong

The end:

This article provides a rough specification for Objective-C coding and some simple suggestions. We welcome you to complement and improve it, communicate progress together, maintain and enhance the legibility, scalability, robustness and so on of the project code