iOS4.0開始,Block橫空出世,它其實就是c預言的補充,書面點說就是帶有自動變量的匿名函數,Block簡潔,代碼的可讀性也高,所以深受廣大開發者的喜好,這一次給你們介紹Block的基本類型和項目中的實際操做。ide
Block的形式以下:函數
void(^tempBlock)() = ^(){ NSLog(@"無參無返回值"); }; //調用 tempBlock();
int(^tempBlock)() = ^(){ return 10; }; //調用的時候,不管你輸入的是什麼都返回的是10; tempBlock(100);
void(^tempBlock)(int) = ^(int temp){ NSLog(@"有參數無返回值"); };
int(^tempBlock)(int) = ^(int number){ return number; }; //輸入多少打印就是多少 tempBlock(100);
__block int x = 100; void(^sumXWithYBlock)(int) = ^(int y){ x = x + y; NSLog(@"new value %d",x); }; //打印的值就是x+y,100+100=200 sumXWithYBlock(100);
//1.在第二個頁面(SecondViewController)首先聲明一個屬性 /** 先聲明block的名字,並肯定參數的類型 */ @property(nonatomic,copy)void (^netViewBlock)(NSString *text); //2.在點擊按鈕返回的時候,往回傳你須要傳的參數,參數類型要一致 -(void)back{ self.netViewBlock(@"你好"); [self.navigationController popViewControllerAnimated:YES]; }
-(void)click:(UIButton *)sender{ //把第二頁的返回的值顯示在label上 UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(30, 100, 200, 30)]; [self.view addSubview:label]; SecViewController *vc = [[SecViewController alloc] init]; vc.netViewBlock = ^(NSString *text){ label.text = text; }; [self.navigationController pushViewController:vc animated:YES]; }
例子:點擊Button,須要改變Button的title工具
實現:atom
1.建立一個工具類,聲明一個類方法,並自定義一個block,須要傳title,因此傳參類型是NSStringspa
@interface ChangeBuTitleTool : NSObject +(void)changeBuTitleWithText:(void(^)(NSString *titleText))text; @end
2.實現.net
@implementation ChangeBuTitleTool +(void)changeBuTitleWithText:(void(^)(NSString *titleText))text{ if (text) { text(@"tyler"); } } @end
3.在控制器裏Button的點擊的時候,實現改變title的方法code
-(void)addButton{ UIButton *bu = [UIButton buttonWithType:(UIButtonTypeCustom)]; bu.backgroundColor = [UIColor blueColor]; bu.frame = CGRectMake(30, 90, 100, 50); [self.view addSubview:bu]; [bu addTarget:self action:@selector(click:) forControlEvents:(UIControlEventTouchUpInside)]; } -(void)click:(UIButton *)sender{ [ChangeBuTitleTool changeBuTitleWithText:^(NSString *titleText) { [sender setTitle:titleText forState:(UIControlStateNormal)]; }]; }
4.Block與typedef的結合orm
在上一個例子中,聲明一個類方法,其中定義block直接寫在類方法裏,看起來很不和諧,尤爲是對新手看起來可讀性不過高,能夠用typedef單獨定義一個block,增長代碼的可讀性。blog
typedef void (^titleBlock)(NSString *titleText); @interface ChangeBuTitleTool : NSObject +(void)changeBuTitleWithText:(titleBlock)text; //+(void)changeBuTitleWithText:(void(^)(NSString *titleText))text; @end @implementation ChangeBuTitleTool +(void)changeBuTitleWithText:(titleBlock)text{ if (text) { text(@"tyler"); } } @end
Block入門篇就介紹到這裏,下期更精彩!<( ̄︶ ̄)>開發