之前一直沒有使用masonry,最近因為比較閒,就嘗試使用了下masonry,但是masonry這種和objec-c大相庭徑的寫法,搞得我有點懵逼,於是今天簡單學習了一下鏈式程式設計。為了鞏固知識,於是有了這篇文章。不足之處希望大家不吝賜教。
在筆者的理解中,其實鏈式程式設計相對於我們常用的方法,最大的區別在於返回值,我們通常返回值型別為void 或其他型別的值,而鏈式程式設計返回的卻是block,而block又返回了物件本身,而類方法也可以根據我們的需求來返回類物件或者作為初始化方法返回乙個物件。而且可以多個方法之間可以任意呼叫,基本上可以無限呼叫下去,確實很像鍊子。莫非這就是鏈式程式設計的名字的由來嘛。。?
下面結合**來~
建立乙個person類,直接貼**
其中3是無返回值無參,4是有返回值無參,5是有返回值有參,最後兩個 是有返回值多參。eat 和 sleep分別對應兩種寫法。eatandsleep是為了驗證筆者的猜想,將block作為返回值,結果證明猜想正確。
#import ns_assume_nonnull_begin
@class person;
typedef person*(^eatandsleep3)(nsstring *food, nsinteger hour);
@inte***ce person : nsobject
- (void)eat1;
- (void)sleep1;
- (person *)eat2;
- (person *)sleep2;
- (void(^)(void))eat3;
- (void(^)(void))sleep3;
- (person *(^)(void))eat4;
- (person *(^)(void))sleep4;
- (person *(^)(nsstring* name))eat5;
- (person *(^)(nsinteger hour))sleep5;
- (person *(^)(nsstring *food, nsinteger hour))eatandsleep1;
- (person *(^)(nsstring *food, nsinteger hour))eatandsleep2;
- (eatandsleep3)eatandsleep3;
@end
ns_assume_nonnull_end
繼續貼上呼叫的**#import "person.h"
@implementation person
- (void)eat1
- (void)sleep1
- (person *)eat2
- (person *)sleep2
- (void(^)(void))eat3 ;
return eat3block;
}- (void(^)(void))sleep3 ;
}- (person *(^)(void))eat4 ;
return eat4block;
}- (person *(^)(void))sleep4 ;
}- (person *(^)(nsstring* name))eat5 ;
return eat5block;
}- (person *(^)(nsinteger hour))sleep5 ;
}- (person *(^)(nsstring *food, nsinteger hour))eatandsleep1 ;
return eatandsleep1block;
}- (person *(^)(nsstring *food, nsinteger hour))eatandsleep2 ;
}- (eatandsleep3)eatandsleep3 ;
}@end
然後執行結果person *person = [person new];
[person eat1];
[person sleep1];
nslog(@"\n");
[[person eat2] sleep2];
nslog(@"\n");
person.eat3();
person.sleep3();
nslog(@"\n");
person.eat4().sleep4();
nslog(@"\n");
person.sleep4().eat4();
nslog(@"\n");
person.sleep5(3).eat5(@"大閘蟹");
nslog(@"\n");
person.eatandsleep1(@"河豚",10).eatandsleep2(@"乙隻牛", 20);
nslog(@"\n");
person.eatandsleep3(@"速食麵",1);
以上就是關於鏈式程式設計的校驗demo
為了測試學習成果,自己又對uiview常用的一些方法,採用鏈式程式設計的方式,寫了乙個category。各位也可以自己嘗試一下。
手動碼字不易。+ (uiview *(^)(cgfloat x, cgfloat y, cgfloat width, cgfloat height))zhh_viewwithframe;
- (uiview *(^)(uicolor *color))zhh_setbackgroundcolor;
- (uiview *(^)(cgfloat radius))zhh_setcornerradius;
- (uiview *(^)(cgfloat alpha))zhh_setalpha;
- (uiview *(^)(uiview *superview))zhh_setsuperview;
- (uiview *(^)(tapaction tapblock))zhh_settapaction;
iOS中的鏈式程式設計
ios開發過程中鏈式程式設計平時運用的最多的應該就是 masonry的約束,剛開始用masonry時就感覺莫名其妙,只是按照規則用 把一系列設定連線起來,感覺可讀性很好並沒有深入 偶爾看到鏈式程式設計的思想,就是以masonry舉得例子,才認識到這其實是一種讓 可讀性更強,也能提高開發效率的一種思想...
iOS鏈式程式設計
nsinteger result adder.add 4 sub 1 mult 2 div 3 表示 4 1 2 3,是不是很方便很直觀。我們知道,如果是c 的實現話鏈式操作是很簡單的,因為c 的函式呼叫就是通過點操作呼叫的,只需要返回物件本身就可以實現鏈結了。但是oc就不行了,因為oc的點操作表示...
ios鏈式程式設計
首先我們看一下使用masonry對控制項進行布局的 格式。self.bottomview1 mas makeconstraints masconstraintmaker make 上邊這段 有特點 使用點語法 可以進行鏈式呼叫 那麼實現鏈式程式設計就需要解決上邊兩個問題。function.h imp...