[Objective-C] 020_ Block
1.定義和使用Block
運行結果:
通過運行上面的簡單代碼示例,可以得知:
[1].在類中,定義一個Block變量,就像定義一個函數。
[2].Block可以定義在方法內部,也可以定義在方法外部。
[3].只有調用Block時候,才會執行其{}體內的代碼。
2.__block關鍵字
在Block的{}體內,是不可以對外面的變量進行更改的,將會報錯(Variable is not assigning (missing __block type)),比如下面:
要如何更正才能對外面的值呢?通過添加__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:
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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【翻译自mos文章】job 不能自己主动
- 下一篇: cro概念股有哪些 关注这些上市公司就