早上看了位仁兄寫了 ! 《Swift:讓人眼前一亮的初始化方式》的文章 。什麼?!初始化?Objective-C!好吧,嚇哔哔~~~
一、普通程序猿
普通程序員使用最常見路人姿勢等場。普普通通,純屬陸仁輩。
陸仁賈寫法:
// view 1 UIView *v1 = [UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 100)]; v1.backgroundColor = [UIColor whiteColor]; // view 2 UIView *v2 = [UIView alloc] initWithFrame:CGRectMake(0, 120, 200, 100)]; v2.backgroundColor = [UIColor whiteColor]; // add to view [self.view addSubview:v1]; [self.view addSubview:v2];
撸人已寫法:撸人已明顯比陸仁賈聰明多了。使用大括號隔離,view1與view2相互獨立,創建代碼變量不會相互污染。
// view 1 { UIView *v1 = nil; UIView *v = [UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 100)]; v.backgroundColor = [UIColor whiteColor]; v1 = v; [self.view addSubview:v1]; } // view 2 { UIView *v2 = nil; UIView *v = [UIView alloc] initWithFrame:CGRectMake(0, 120, 200, 100)]; v.backgroundColor = [UIColor whiteColor]; v2 = v; [self.view addSubview:v2]; }
路人餅寫法
// view 1 UIView *v1 = nil; { UIView *v = [UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 100)]; v.backgroundColor = [UIColor whiteColor]; v1 = v; } // view 2 UIView *v2 = nil; { UIView *v = [UIView alloc] initWithFrame:CGRectMake(0, 120, 200, 100)]; v.backgroundColor = [UIColor whiteColor]; v2 = v; } [self.view addSubview:v1]; [self.view addSubview:v2];
二、文藝程序猿
文藝程序猿,使用教科書姿勢登場。使用builder模式。使用block隔離初始化代碼。
首先給NSObject增加擴展接口
// 擴展NSObject,增加Builder接口 @interface NSObject (Builder) + (id)z0_builder:(void(^)(id that))block; - (id)z0_builder:(void(^)(id that))block; @end // 實現 @implementation NSObject (Builder) + (id)z0_builder:(void(^)(id))block { id instance = [[self alloc] init]; block(instance); return instance; } - (id)z0_builder:(void(^)(id))block { block(self); return self; } @end
使用。代碼簡潔工整。處處都是文藝范。
- (void) foo { // 使用 // view 1 UIView *v1 = [UIView z0_builder:^(UIView *that) { that.frame = CGRectMake(0, 0, 320, 200); that.background = [UIColor whiteColor]; }]; // view 2 UIView *v2 = [[UIView alloc] init]; [v2 z0_builder:^(UIView *that) { that.frame = CGRectMake(0, 0, 320, 200); that.background = [UIColor whiteColor]; }]; // 添加到父視圖 [self.view addSubview:v1]; [self.view addSubview:v2]; }
三、二逼程序猿
最後入場的是二逼程序猿。
!#!@#@%&……&%¥%!@#¥!@#¥!!!!! 這個是什麼卵?
其實....我也不知道!>_<# 自行領悟。
黑科技?????呵呵~~ 我就是代碼少,你吹啊~~
- (void) foo { // view 1 UIView *v1 = ({ UIView *v = [UIView alloc] init]; v.frame = CGRectMake(0, 0, 320, 200); v.background = [UIColor whiteColor]; v; }); // view2 UIView *v2 = ({ UIView *v = [UIView alloc] init]; v.frame = CGRectMake(0, 120, 320, 200); v.background = [UIColor blueColor]; v; }); [self.view addSubview:v1]; [self.view addSubview:v2]; }