日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

[Objective-C] 020_ Block

發布時間:2024/10/12 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [Objective-C] 020_ Block 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1.定義和使用Block

1 #import "ViewController.h" 2 3 @interface ViewController () 4 5 @end 6 7 @implementation ViewController 8 9 - (void)viewDidLoad { 10 [super viewDidLoad]; 11 12 //定義block 無返回值,無參數 13 void (^nameBlock)() = ^ () { 14 NSLog(@"姓名: Block"); 15 }; 16 17 //定義block 有返回值,有參數 18 int (^ageBlock)(int) = ^(int age) { 19 NSLog(@"年齡: %d",age); 20 return age + 1; 21 }; 22 23 //調用block 24 nameBlock(); 25 int age = ageBlock(3); 26 NSLog(@"》》》年齡:%d",age); 27 nameAndAgeBlock(@"SD.Team",2015); 28 } 29 30 void (^nameAndAgeBlock)() = ^(NSString *name,int age) { 31 NSLog(@"姓名:%@,年齡:%d",name,age); 32 }; 33 34 - (void)didReceiveMemoryWarning { 35 [super didReceiveMemoryWarning]; 36 } 37 38 @end 39 40 Block 定義與使用

  運行結果:
  
  通過運行上面的簡單代碼示例,可以得知:
    [1].在類中,定義一個Block變量,就像定義一個函數。
    [2].Block可以定義在方法內部,也可以定義在方法外部。
    [3].只有調用Block時候,才會執行其{}體內的代碼。

2.__block關鍵字

  在Block的{}體內,是不可以對外面的變量進行更改的,將會報錯(Variable is not assigning (missing __block type)),比如下面:

1 - (void)viewDidLoad { 2 [super viewDidLoad]; 3 int myAge = 25; 4 void (^updateAge)(int) = ^(int age){ 5 myAge = myAge + age; 6 NSLog(@"age:%d",myAge); 7 }; 8 }

  要如何更正才能對外面的值呢?通過添加__block 關鍵字即可

1 - (void)viewDidLoad { 2 [super viewDidLoad]; 3 __block int myAge = 25; 4 void (^updateAge)(int) = ^(int age){ 5 myAge = myAge + age; 6 NSLog(@"age:%d",myAge); 7 }; 8 9 updateAge(3); 10 }


3.Block作為property屬性

  如有一需求:在ViewController中,點擊設置按鈕,push到下一個頁面SettingViewController,在SettingViewController的age輸入框TextField中更新年齡,返回的時候,在ViewController的年齡Label上面顯示已更新的年齡。可以通過delegate 來實現,delegate前面講過了,這次我們就用block來實現.
  SettingViewController:

1 //SettingViewController.h 文件 2 @interface SettingViewController : UIViewController 3 @property (nonatomic, copy) void (^updateAgeBlock)(NSString *age); 4 5 @end 6 7 //SettingViewController.m 文件 8 - (IBAction)updateAgeBtnClicked:(id)sender { 9 if (self.updateAgeBlock) { 10 self.updateAgeBlock(self.ageTextField.text); 11 } 12 [self.navigationController popViewControllerAnimated:YES]; 13 }

  ViewController:

1 - (IBAction)settingClicked:(id)sender 2 { 3 SettingViewController *settingVC = [[SettingViewController alloc] initWithNibName:@"SettingViewController" bundle:nil]; 4 settingVC.updateAgeBlock = ^(NSString *age){ 5 [self updateAgeLabel:age]; 6 }; 7 [self.navigationController pushViewController:settingVC animated:YES]; 8 } 9 10 - (void)updateAgeLabel:(NSString *)age 11 { 12 self.ageLabel.text = age; 13 }

我們通過block方式同樣達到了delegate的效果。

轉載于:https://www.cnblogs.com/superdo/p/5081115.html

總結

以上是生活随笔為你收集整理的[Objective-C] 020_ Block的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。