The code specification is one that we’ve been following since we started in the industry. Can, of course, that there is no clear norms, is the company’s internal discuss finalised a code specifications, can also use the online calls for higher code standard, the content of the specification are the same, it is focused on “abide by”, this requires that all developers to maintain together.

But everyone’s code habits are certainly different. If you want to implement the new code specification thoroughly, here is a solution to share with you.

primers

Most of the time, when we enter the company, we continue to maintain mature projects that have been launched, so the project has a certain amount of code. If we start to make code specifications at this time, we must do new code based on subsequent new requirements. If there is a less tense development cycle, we will do the transformation of old code.

How to make code specifications is unnecessary here, because each company can not be completely the same, all need to make their own specifications according to the characteristics of each company project. After the specification is established, there may be some problems in implementation. Due to years of code habits, it is not easy for everyone to ensure that every line of code is written in accordance with the code specification. When submitting the code, it takes a lot of energy for those who review the code to review the code specification line by line. Clearly not what a programmer should do.

So we need to think about how we can make the code specification more efficient.

Here are two simple and efficient ways to implement it:

  1. CodeSnippets
  2. Xcode class template

CodeSnippets

CodeSnippets can be added manually in Xcode by selecting any line of Code and right clicking Create CodeSnippet

Creating snippets you’ve probably used this before, but it’s very convenient, and once you’ve created it, you can use it just like using a shortcut key, and you can put in the edited snippets with one click

Parameter interpretation

Title: name (snippet name).

Summary: What is the code snippet for?

Platform: Specifies a Platform (All, iOS, macOS, tvOS, or watchOS).

Language: The functional Language, such as Objective-C.

Completion Shortcut: a Shortcut to a snippet of code (such as a snippet that comes out in a for loop when you type for).

Completion: Select All in the Scopes Scopes (e.g., in the extension interface, in the method, etc.) without specifying any specific requirements.

White space: Editable snippets of code.

automation

With the CodeSnippets tool, you already know how to use it to improve the efficiency of our code specification. That is, make all the specifications into CodeSnippets and add them to your computer’s Xcode, so that you can turn over most of the specification to CodeSnippets, which improves the efficiency of development, and also improves the efficiency of the code specification.

We create CodeSnippets kept in ~ / Library/Developer/Xcode/UserData under this path, when you change the computer, can go to backup a copy of all the CodeSnippets under this path, return to the path to the new computer, you can use. Very convenient.

So we only need to create CodeSnippets once, and then export the CodeSnippets to the cloud so that all users can download and install it themselves. At the end of this article I will include a CodeSnippets for you to download and use.

CodeSnippets snippet introduction

Attribute fragment

My_assign (assign attribute)

@property (nonatomic, assign) <#type#> <#name#>;
Copy the code
  1. My_copy (Copy property)
@property (nonatomic, copy) <#type#> *<#name#>;
Copy the code

3. My_strong (strong attribute)

@property (nonatomic, strong) <#type#> *<#name#>;
Copy the code

4. My_weak (weak attribute)

@property (nonatomic, weak) <#type#> *<#name#>;
Copy the code

Methods pieces

1. My_createCollectionView (Create collectionView collection)

@property (nonatomic, strong) UICollectionView *collectionView; @property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout; #pragma mark - UICollectionView DataSource and Delegate - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { return <#numbers#>; } - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { <#collectionViewcell#> *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath]; return cell; } - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath { } - (UICollectionViewFlowLayout *)flowLayout{ if (! _flowLayout) { _flowLayout = [[UICollectionViewFlowLayout alloc]init]; _flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical; _flowLayout.itemSize = CGSizeMake(<#width#>,<#height#>); _flowLayout.minimumInteritemSpacing = <#CGFloat#>; _flowLayout.minimumLineSpacing = <#CGFloat#>; } return _flowLayout; } static NSString *const identify = @"collectionViewCell"; - (UICollectionView *)collectionView { if (! _collectionView) { _collectionView = [[UICollectionView alloc] init]; _collectionView = [[UICollectionView alloc] initWithFrame:<#frame#> collectionViewLayout:self.flowLayout]; _collectionView.backgroundColor = [UIColor whiteColor]; [_collectionView registerClass:[<#collectionViewcell#> class] forCellWithReuseIdentifier:identify]; _collectionView.dataSource = self; _collectionView.delegate = self; } return _collectionView; }Copy the code

2. My_createTableView (create tableView method set)

@property (nonatomic, strong) UITableView *tableView; # pragma mark - UITableViewDataSource / / set the number of Sections - (NSInteger) numberOfSectionsInTableView tableView: (UITableView *) {  return <#NSInteger number#>; } // set the number of rows - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {return <#NSInteger number#>; } // set cell contents - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *Identifier = <#NSString identifier#>; <#UITableViewCell cell#> *cell = [tableView dequeueReusableCellWithIdentifier:Identifier]; if (cell==nil) { cell = [[<#UITableViewCell cell#> alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifier]; [cell setSelectionStyle:UITableViewCellSelectionStyleNone]; } return cell; } #pragma mark - UITableViewDelegate // set cell height - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return <#CGFloat height#>; } / / set the height of the Sections - CGFloat tableView: (UITableView *) tableView heightForHeaderInSection: (NSInteger) section {return <#CGFloat height#>; } // Cell click event - (void)tableView (UITableView *)tableView didSelectRowAtIndexPath (NSIndexPath *)indexPath {} - (UITableView *)tableView { if (! _tableView) { _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain]; _tableView.delegate = self; _tableView.dataSource = self; _tableView.backgroundColor = [UIColor clearColor]; / / cell line style [_tableView setSeparatorStyle: UITableViewCellSeparatorStyleNone]; } return _tableView; }Copy the code

3. My_funsIns (instance method)

- (<#return#>)<#funcName#> {
	<#doSomeThing#>
}
Copy the code

4. My_diffentStr (attribute string method)

- (NSMutableAttributedString *)setAttrStr:(NSString *)str subText:(NSString*)subText {
    NSString *string = [NSString stringWithFormat:@"%@", str];
    NSRange range = [string rangeOfString:subText];
    NSMutableAttributedString *aString = [[NSMutableAttributedString alloc] initWithString:string];
    [aString setAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:FONT_SIZE_14], NSForegroundColorAttributeName:UIColorFromRGB(0xdbac6f)}
                     range:range];
    return astring;
}
Copy the code

5. My_getBtn (button get method)

- (UIButton *)<#UIButton#> { if (! _<#UIButton#>) { _<#UIButton#> = [UIButton buttonWithType:UIButtonTypeCustom]; [_<#UIButton#> setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal]; [_<#UIButton#> addTarget:self action:@selector(<#UIButton#>Fun) forControlEvents:UIControlEventTouchDown]; } return _<#UIButton#>; }Copy the code

6. My_getImageView (mageView get method)

- (UIImageView *)<#UIImageView#> { if (! _<#UIImageView#>) { _<#UIImageView#> = [[UIImageView alloc] init]; } return _<#UIImageView#>; }Copy the code

7. My_getLabel (label get method)

- (UILabel *)<#UILabel#> { if (! _<#UILabel#>) { _<#UILabel#> = [[UILabel alloc] init]; _<#UILabel#>.textColor = ; _<#UILabel#>.font = ; } return _<#UILabel#>; }Copy the code

8. My_getView (view get method)

- (UIView *)<#UIView view#> { if (! _<#UIView view#>) { _<#UIView view#> = [[UIView alloc] init]; } return _<#UIView view#>; }Copy the code

9. My_getCustomClass (Custom type get method)

- (<#class#> *)<#class#> { if (! _<#class#>) { _<#class#> = [[<#class#> alloc] init]; } return _<#class#>; }Copy the code

A code snippet within a method

1. My_shadow (View shadow)

<#view#>.layer.shadowColor = <#color#>.CGColor; <#view#>.layer.shadowRadius = 3; <#view#>.layer.shadowOffset = CGSizeMake(0, 2); < # view# >. Layer. ShadowOpacity = 0.1;Copy the code

2. My_shadowStr (set font with shadow)

NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:<#title#>]; UIFont *baseFont = [UIFont systemFontOfSize:<#(CGFloat)#>]; [attrString addAttribute:NSFontAttributeName value:baseFont range:NSMakeRange(0, [<#title#> length])]; Setup all the font / / / / set the color [attrString addAttribute: NSForegroundColorAttributeName value: < # color# > range: NSMakeRange (0, [<#title#> length])]; NSShadow *shadow = [[NSShadow alloc] init]; shadow.shadowColor = <#shadowColor#>; shadow.shadowOffset = CGSizeMake(0, 2); shadow.shadowBlurRadius = 5; [attrString addAttribute:NSShadowAttributeName value:shadow range:NSMakeRange(0, [<#title#> length])];Copy the code

3. My_weakSelf (Block Weiself)

__weak typeof(self) weakSelf = self;
Copy the code

Class template

The term “class template” may not be so familiar, but it is also a development day to use things, but before we all use the system, now you can try to customize a template.

Each item above is a template defined by the system for us. For example, the template code corresponding to the first item Source is placed in/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/Xcode/Templates/File\ Templates/iOS/SourceThis path right here.

Create a new folder, go to Source and copy all the files, and then modify them according to your code specification, which is the specification for creating a new class. For example, to create a class that inherits from NSObject, the template in the.h file automatically adds the following:

#import <Foundation/ foundation.h > #pragma mark - @class #pragma mark - constant #pragma mark - enumeration NS_ASSUME_NONNULL_BEGIN /** Note <# additional notes to note some points that need to be noted. There is no way to cancel this item. #> */ @interface TestNSObject : NSObject @end NS_ASSUME_NONNULL_ENDCopy the code

For example, to create a class that inherits from UIViewController, we can customize a lot of things in advance. Many rules in the code specification can be directly written into the code, which increases the readability of the code and saves a lot of time to write repetitive code.

#import "testViewController. h" #pragma mark - @class #pragma mark - constant #pragma mark - enumeration @interface TestViewController () #pragma mark - Life Cycle - (void)viewDidLoad {[super viewDidLoad]; [self configureNavigationbar]; [self createSubViews]; [self createSubViewsConstraints]; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; } - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } - (void)dealloc { NSLog(@"%@ - dealloc", NSStringFromClass([self class])); } #pragma mark - Events #pragma mark - UITextFieldDelegate #pragma mark - UITableViewDataSource #pragma mark - UITableViewDelegate #pragma mark - UIOtherComponentDelegate #pragma mark - Custom Delegates #pragma mark - Public Pragma mark - Private pragma - (void)configureNavigationbar {self.title = <# title #>; } / / add child views - (void) createSubViews {} / / add restrictions - (void) createSubViewsConstraints {} # pragma mark - Getters and Setters @endCopy the code

portal

I hope the automation scheme of these code specifications shared above will be helpful to you. I have uploaded all of them to Git for easy access. It’s easy to use:

Script installation

  1. Download Template_CodeSnippets. Zip

  2. Open your terminal and CD to CodeSnippetsAndXcodeTemplates folder

  3. Enter./ codesnippetsInstall. sh on the terminal to run the script to install CodeSnippets

  4. Input. / ClassTemplateInstall. Sh run the script to install a Class template, according to the prompt for password Can.

  5. The Class template uses: Restart Xcode and select MY Cocoa Touch Calss when creating a new file.

6. Use CodeSnippets: just type in the shortcut words where you need to enter CodeSnippets (see figure below).

Manual installation and use of class template:

  1. Open go to folder copy and paste path: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/Xcode/Templates/File Templates/Source

  2. Drag the MY Cocoa Touch Class.xctemplate file into the current folder.

  3. Restart Xcode and select when creating a new file

Manual installation and usage of CodeSnippets:

  1. Open go to folder copy and paste path: ~/Library/Developer/Xcode/UserData/CodeSnippets
  2. If going fails, go to:~/Library/Developer/Xcode/UserDataIn the.
  3. Drag the contents of the CodeSnippets file into the current folder.
  4. If you do not have the CodeSnippets folder, add the decompressed folder to UserData directly.
  5. Enter a shortcut where you need to enter a snippet.