我的链式编程

来源:互联网 发布:oracle 锁表sql 编辑:程序博客网 时间:2024/05/23 11:09

在编写代码时,通过点(.)调用的方式,将代码连接成一行,大大增加了代码的可读性,这就是链式编程。

实现链式编程的关键就是声明一个block的属性,而这个block返回值必须还是一个对象(根据业务需求不同,可以返回的是这个对象实例本身,也可以是这个类的另一个实例,更可以是另一个类的实例对象)。而block中内部的逻辑就是项目的业务逻辑。

注意事项
1 不需要考虑调用顺序,只需要知道考虑结果
2 把操作尽量写成一系列嵌套的函数或者方法调用
3 每个方法必须有返回值(本身对象),把函数或者Block当做参数,block参数(需要操作的值)block返回值(操作结果)

创建UILabel的类别文件,并实现自定义的block属性,以实现链式编程。

+ (UILabel *)newUILabel:(void (^)(UILabel *))newlabel;- (UILabel *(^)(CGRect))labelFrame;- (UILabel *(^)(UIView *))labelSuperview;- (UILabel *(^)(UIFont *))labelFont;- (UILabel *(^)(UIColor *))labelColor;- (UILabel *(^)(NSTextAlignment))labelAlignment;- (UILabel *(^)(NSString *))labelText;- (UILabel *(^)(UIColor *))labelBackgroundColor;
+ (UILabel *)newUILabel:(void (^)(UILabel *))newlabel{    UILabel *label = [[UILabel alloc] init];    newlabel(label);    return label;}- (UILabel *(^)(CGRect))labelFrame{    return ^(CGRect rect) {        self.frame = rect;        return self;    };}- (UILabel *(^)(UIView *))labelSuperview{    return ^(UIView *view) {        [view addSubview:self];        return self;    };}- (UILabel *(^)(UIFont *))labelFont{    return ^(UIFont *font) {        self.font = font;        return self;    };}- (UILabel *(^)(UIColor *))labelColor{    return ^(UIColor *textColor) {        self.textColor = textColor;        return self;    };}- (UILabel *(^)(NSTextAlignment))labelAlignment{    return ^(NSTextAlignment alignment) {        self.textAlignment = alignment;        return self;    };}- (UILabel *(^)(NSString *))labelText{    return ^(NSString *text) {        self.text = text;        return self;    };}- (UILabel *(^)(UIColor *))labelBackgroundColor{   return ^(UIColor *color) {       self.backgroundColor = color;       return self;   };}
// 实例化[UILabel newUILabel:^(UILabel *label) {        label.labelFont([UIFont systemFontOfSize:12.0])        .labelColor([UIColor redColor])        .labelSuperview(self.view)        .labelFrame(CGRectMake(10.0, currentView.bottom + 10.0, 120.0, 30.0))        .labelBackgroundColor([UIColor colorWithWhite:0.5 alpha:0.2])        .labelAlignment(NSTextAlignmentCenter)        .labelText(@"链式编程实例化");    }];

效果图.png

原创粉丝点击