国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

iOS階段學習第24天筆記(Block的介紹)

2019-11-14 18:40:06
字體:
來源:轉載
供稿:網友

iOS學習(OC語言)知識點整理

一、Block 的介紹  

1)概念:

    block 是一種數據類型,類似于C語言中沒有名字的函數,可以接收參數,也可以返回值與C函數一樣被調用

     封裝一段代碼 可以在任何地方調用 block 也可以作為函數參數,以及函數返回值  

2)Block 實例代碼  

 1 //定義了一個block類型MyBlock,MyBlock類型的變量只能指向帶兩個int的參數和返回int的代碼塊  2 typedef int (^MyBlock)(int,int);  3 //定義一個函數指針  4 int (*pMath)(int ,int);  5  6 int add(int a,int b)  7 {  8     return a+b;  9 }10 11 int sub(int a,int b) 12 { 13     return a-b; 14 }15 16 int main(int argc, const char * argv[]) { 17     @autoreleasepool { 18         pMath = add;//指向函數指針 19         //NSLog(@"sum: %d",pMath(2,3)); 20         pMath = sub; 21 22         //定義了一個block,block只能指向帶2個int的參數,返回int的代碼塊  23         //以^開始的為代碼塊,后面()是參數,然后{}代碼塊 24         int (^bloke1)(int,int) = ^(int a,int b){ 25             return a+b; 26         };27 28         int s = bloke1(3,5); 29         NSLog(@"s:%d",s);  30         //定義一個block指向沒有參數沒有返回值的代碼塊(沒有參數,void可以省略) 31         void (^block2)(void) = ^{ 32             NSLog(@"PRograming is fun!"); 33         }; 34         block2(); 35         int (^block3)(int,int) = ^(int a,int b ){ 36             return a-b; 37 38         }; 39 40         //定義了MyBlock類型的變量,賦值代碼塊 41         MyBlock block4 = ^(int a,int b){ 42             return a*b; 43         };44 45         NSLog(@"%d",block4(2,5)); 46 47         int c = 10; 48         __block int d = 1; 49         //block塊可以訪問塊外的變量但是不能修改,如果需要修改,變量前加上__block修飾 50         void (^block5)(void) = ^{ 51             d = d+2; 52             NSLog(@"c:%d,d:%d",c,d); 53         }; 54         block5(); 55     } 56     return 0; 57 }

3)解決Block互為強引用時的警告的方法 例如:

1  UIImageView *imgv = [[UIImageView alloc]initWithFrame:CGRectMake(10, 50, 300, 150)];2     [self.view addSubview:imgv];3     4 //使用 __unsafe_unretained 重新定義對象 解決互為強引用的問題5  __unsafe_unretained UIImageView *weakImagev = imgv;6     [imgv setImageWithURL:[NSURL URLWithString:@"http://xxx/xxx.jpg?570x300_120"] withPlaceHolder:nil 7                 competion:^(UIImage *image) {8                     weakImagev.image = image;9 }];

4)有返回值的Block的使用方法 實例代碼: 

//將局部變量聲明為__block,表示將會由block進行操作,比如:   __block float price = 1.99; float (^finalPrice)(int) = ^(int quantity){  return quantity * price;};int orderQuantity = 10;price =0.99;NSLog(@"With block storage modifier - Ordering %d units, final price is: $%2.2f", orderQuantity, finalPrice(orderQuantity)); //此時輸出為With block storage modifier – Ordering 10 units, final price is: $9.90  

 


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 包头市| 大港区| 东乡族自治县| 玉山县| 博客| 灵武市| 大化| 汉中市| 永修县| 石家庄市| 军事| 铁力市| 宁安市| 双柏县| 玛沁县| 江达县| 尉犁县| 望谟县| 崇仁县| 澎湖县| 渝北区| 固镇县| 哈巴河县| 镇远县| 永胜县| 合山市| 汕头市| 民丰县| 西乌珠穆沁旗| 张家口市| 贵港市| 呈贡县| 揭东县| 濮阳市| 临颍县| 榕江县| 景泰县| 正定县| 嘉定区| 临沭县| 永州市|