iOS 生成代码一:属性生成getter
2019-06-17 本文已影响0人
观星
作用:在声明属性后,使用脚本生成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;
}