iOS 生成代碼一:屬性生成getter

作用:在聲明屬性后,使用腳本生成getter
作用:在聲明屬性后,使用腳本生成getter
作用:在聲明屬性后,使用腳本生成getter

純手寫UI的時候,經(jīng)常會定義一堆控件,然后逐個添加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

將上面的內(nèi)容保存為文件中,文件名 getter.sh。

假設 MyCell.m 內(nèi)容如下

@interface MyCell()

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

@end

執(zhí)行腳本grep @property MyCell.m | sh getter.sh

輸出以下內(nèi)容

- (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;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • Swift1> Swift和OC的區(qū)別1.1> Swift沒有地址/指針的概念1.2> 泛型1.3> 類型嚴謹 對...
    cosWriter閱讀 11,665評論 1 32
  • Linux習慣問題: 在vim編輯時,按了ctrl + s后,再按ctrl + q就可以繼續(xù)執(zhí)行了。ctrl + ...
    光著腳的鞋閱讀 4,696評論 0 16
  • 概要 64學時 3.5學分 章節(jié)安排 電子商務網(wǎng)站概況 HTML5+CSS3 JavaScript Node 電子...
    阿啊阿吖丁閱讀 9,851評論 0 3
  • 上高中的時候,隔壁班一位班主任經(jīng)常提到這樣一句話,讓我印象特別深刻。他說:“孤獨是一種境界,而寂寞是一種病”。隨著...
    蕭然_閱讀 408評論 1 5
  • 前言 關于架構(gòu)的文章,博主很早就想寫了,雖說最近比較流行MVVM,但是MVP以及MVC也沒有過時之說,最主要還是要...
    劉望舒閱讀 1,479評論 2 40

友情鏈接更多精彩內(nèi)容