作用:在聲明屬性后,使用腳本生成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;
}