序
早上看了位仁兄写了《Swift:让人眼前一亮的初始化方式》的文章。什么?!初始化?Objective-C!好吧,吓哔哔~~~
一、普通程序猿
普通程序员使用最常见路人姿势等场。普普通通,纯属
陆仁贾写法:
1 // view1 2 UIView *v1 = [UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 100)]; 3 v1.backgroundColor = [UIColor whiteColor]; 4 5 // view2 6 UIView *v2 = [UIView alloc] initWithFrame:CGRectMake(0, 120, 200, 100)]; 7 v2.backgroundColor = [UIColor greenColor]; 8 9 10 [self.view addSubview:v1]; 11 [self.view addSubview:v2];
撸人已写法:撸人已明显比陆仁贾聪明多了。使用大括号隔离,view1与view2相互独立,创建代码变量不会相互污染。
1 // view 1 2 { 3 UIView *v1 = nil; 4 5 UIView *v = [UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 100)]; 6 v.backgroundColor = [UIColor whiteColor]; 7 8 v1 = v; 9 10 [self.view addSubview:v1]; 11 } 12 13 // view 2 14 { 15 UIView *v2 = nil; 16 17 UIView *v = [UIView alloc] initWithFrame:CGRectMake(0, 120, 200, 100)]; 18 v.backgroundColor = [UIColor whiteColor]; 19 20 v2 = v; 21 22 [self.view addSubview:v2]; 23 }
二、文艺程序猿
文艺程序猿,使用教科书姿势登场。使用builder模式。使用block隔离初始化代码。
1. 首先给NSObject增加扩展接口
1 // 扩展NSObject,增加Builder接口 2 @interface NSObject (Builder) 3 4 + (id)z0_builder:(void(^)(id that))block; 5 6 - (id)z0_builder:(void(^)(id that))block; 7 8 @end 9 10 // 实现 11 @implementation NSObject (Builder) 12 13 + (id)z0_builder:(void(^)(id))block { 14 id instance = [[self alloc] init]; 15 block(instance); 16 return instance; 17 } 18 19 - (id)z0_builder:(void(^)(id))block { 20 block(self); 21 return self; 22 } 23 24 @end
2. 使用
1 - (void) foo { 2 // 使用 3 // view 1 4 UIView *v1 = [UIView z0_builder:^(UIView *that) { 5 that.frame = CGRectMake(0, 0, 320, 200); 6 that.backgroundColor = [UIColor whiteColor]; 7 }]; 8 9 // view 2 10 UIView *v2 = [[UIView alloc] init]; 11 [v2 z0_builder:^(UIView *that) { 12 that.frame = CGRectMake(0, 0, 320, 200); 13 that.backgroundColor = [UIColor whiteColor]; 14 }]; 15 16 // 添加到父视图 17 [self.view addSubview:v1]; 18 [self.view addSubview:v2]; 19 }
三、二逼程序猿
最后入场的是二逼程序猿。!#!@#@%&……&%&#¥%!@#¥!@#¥!!!!! 这个是什么卵?是不是🈶啥黑科技?
其实....我也不知道!>_<# 自行领悟。🙄呵呵
好处:
1. 初始化代码隔离。
2. 不需要扩展NSObject类。
1 - (void) foo { 2 // view 1 3 UIView *v1 = ({ 4 UIView *v = [UIView alloc] init]; 5 v.frame = CGRectMake(0, 0, 320, 200); 6 v.backgroundColor = [UIColor whiteColor]; 7 v; 8 }); 9 10 // view2 11 UIView *v2 = ({ 12 UIView *v = [UIView alloc] init]; 13 v.frame = CGRectMake(0, 120, 320, 200); 14 v.backgroundColor = [UIColor blueColor]; 15 v; 16 }); 17 18 [self.view addSubview:v1]; 19 [self.view addSubview:v2]; 20 }
总结
总结个鬼,就几行代码。爱干啥,干啥去~~ 下班闪人~ 白了个掰!