iOS 生成代码一:属性生成getter

作用:在声明属性后,使用脚本生成getter
作用:在声明属性后,使用脚本生成getter
作用:在声明属性后,使用脚本生成getter

纯手写UI的时候,经常会定义一堆控件,然后逐个添加getter。

@property (nonatomic, strong) UILabel *topTitleLabel;
@property (nonatomic, strong) UILabel *contentLabel;

通过下面的脚本,可以自动生成getter

awk '{propertyname=substr($5,2,length($5)-2);
    property="_"propertyname;
    if ($4 == "UILabel") print "- (UILabel *)" propertyname "{\n    if (!"property") {\n        "property" = [[UILabel alloc] init];\n\n        "property".textColor = UIColorFromRGB(0x22222);\n       "property".font = [UIFont systemFontOfSize:12];\n   }\n return "property";\n}\n";
    else if (match($3,assign)) print "";
    else print "- ("$4" *)" propertyname "{\n   if (!"property") {\n        "property" = [["$4" alloc] init];\n }\n return "property"\n}"
}' $1

将上面的内容保存为文件中,文件名 getter.sh。

假设 MyCell.m 内容如下

@interface MyCell()

@property (nonatomic, strong) UILabel *topTitleLabel;
@property (nonatomic, strong) UILabel *contentLabel;

@end

执行脚本grep @property MyCell.m | sh getter.sh

输出以下内容

- (UILabel *)topTitleLabel{
    if (!_topTitleLabel) {
        _topTitleLabel = [[UILabel alloc] init];

        _topTitleLabel.textColor = UIColorFromRGB(0x22222);
        _topTitleLabel.font = [UIFont systemFontOfSize:12];
    }
    return _topTitleLabel;
}

- (UILabel *)contentLabel{
    if (!_contentLabel) {
        _contentLabel = [[UILabel alloc] init];

        _contentLabel.textColor = UIColorFromRGB(0x22222);
        _contentLabel.font = [UIFont systemFontOfSize:12];
    }
    return _contentLabel;
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,674评论 1 32
  • Linux习惯问题: 在vim编辑时,按了ctrl + s后,再按ctrl + q就可以继续执行了。ctrl + ...
    光着脚的鞋阅读 4,701评论 0 16
  • 概要 64学时 3.5学分 章节安排 电子商务网站概况 HTML5+CSS3 JavaScript Node 电子...
    阿啊阿吖丁阅读 9,874评论 0 3
  • 上高中的时候,隔壁班一位班主任经常提到这样一句话,让我印象特别深刻。他说:“孤独是一种境界,而寂寞是一种病”。随着...
    萧然_阅读 409评论 1 5
  • 前言 关于架构的文章,博主很早就想写了,虽说最近比较流行MVVM,但是MVP以及MVC也没有过时之说,最主要还是要...
    刘望舒阅读 1,482评论 2 40

友情链接更多精彩内容