iOS代码块(CodeSnippets)你值得拥有:大大提升编码效率

1,580 阅读2分钟

小实验

@property (nonatomic, assign) NSInteger age;

上面的代码,如果是你,你平时怎么在 Xcode 中敲写的呢?

第一种:从左到右依次敲写

011

第二种:采用Code Snippet

031

通过我们的肉眼观察,可以很容易的发现:第二种明显更快

眼见为虚,那好,我们用数据来说话(控制变量法 + 录屏):

唯一不可控的是我在敲代码时的反应,暂且忽略不计。

003

第一种用时 14秒,第二种用时及 3秒,可以看出,差别还是很大的说实在的,我自己之前也一直觉得第二种效率更高,但是没想过如此之高)。

代码块(Code Snippet)

代码块(Code Snippet),顾名思义,就是一个代码片段

如何自定义代码块

010

011

创建代码块

注意下图圈中,对应的颜色(左边是敲代码时展示的效果,右边是代码块的配置)。

001

这里注意要选择Objective-C(默认是Objective-C++),否则扩展(extension)中无效。

002

系统提供的代码块

  • dispatch_oncedispatch_after

004

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        <#code to be executed once#>
    });
    return YES;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(<#delayInSeconds#> * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        <#code to be executed after a specified delay#>
    });
  • forfor...in... 005
    for (<#initialization#>; <#condition#>; <#increment#>) {
        <#statements#>
    }
    
    for (<#type *object#> in <#collection#>) {
        <#statements#>
    }

自定义的代码块

格式:<#注释#>

属性

006

  • 关键字属性

    @property (nonatomic, strong) <#ClassName#> *<#propertyName#>;
    
    /// <#注释#>
    @property (nonatomic, strong) <#ClassName#> *<#propertyName#>;
    
    @property (nonatomic, assign) <#TypeName#> <#propertyName#>;
    
    /// <#注释#>
    @property (nonatomic, assign) <#TypeName#> <#propertyName#>;
    
  • 具体属性

    @property (nonatomic, strong) UILabel *<#XX#>Label;
    
    /// <#注释#>
    @property (nonatomic, strong) UILabel *<#XX#>Label;
    
    @property (nonatomic, copy) NSString *<#propertyName#>;
    
    /// <#注释#>
    @property (nonatomic, copy) NSString *<#propertyName#>;
    

懒加载

008

  • UILabel/UIImageView等的懒加载

    - (UILabel *)<#yourLabel#>
    {
        if (!_<#yourLabel#>) {
            _<#yourLabel#> = [[UILabel alloc] init];
        }
        return _<#yourLabel#>;
    }
    
    - (UIImageView *)<#yourImageView#>
    {
        if (!_<#yourImageView#>) {
            _<#yourImageView#> = [[UIImageView alloc] init];
        }
        return _<#yourImageView#>;
    }
    
  • NSArray/NSMutableArray有泛型的懒加载

    - (NSMutableArray<<#GenericsName#> *> *)<#yourMArray#>
    {
        if (!_<#yourMArray#>) {
            _<#yourMArray#> = [NSMutableArray array];
        }
        return _<#yourMArray#>;
    }
    
  • NSArray/NSMutableArray无泛型的懒加载

    - (NSMutableArray *)<#yourMArray#>
    {
        if (!_<#yourMArray#>) {
            _<#yourMArray#> = [NSMutableArray array];
        }
        return _<#yourMArray#>;
    }
    

方法调用

  • delegate先判断再执行 009

  • Masonry使用 007

其它

Every or any, if you want!

代码块的优点

  • 避免重复代码反复敲写,减少不必要的时间浪费 (如小实验的实验
  • 快速演示(详见每年的WWDC
  • 不常用的方法,可以特殊处理(我一般用来处理个别系统适配)。
  • 统一编码规范

最后

代码块(Code Snippet)真的是个很好用的东东,平时闲了,可以整理一份适合自己的代码块,然后通过GitHub进行备份。如果不想整理,也可以去GitHub搜一些拿来用,但我真的建议还是自己整理一份。