首先要说明 Block并非是必须的,Block在oc中引入仅仅只是为了让开发者更加快速,让代码更加可控可读。
如果你习惯了Block的使用, 那么你肯定会爱上它
1:相对delegate, Block可以让代码更加紧凑,又不失能够进行异步流程的特性。
2:相对于notification, Block可以严格按照1v1的准则发送消息,并且Block的结构更加友好。
3:相对于C语言的特性,block可以使用外边变量,并且有自己的内存管理机制。
4:相对于传统的callback函数,block更加符合objective-c的开发风格。
Block遵循下面所示的结构:
<返回值类型> + ^<Block名字>(形参类型1, 形参类型2……) = ^(实参类型1,实参类型2......){
// block 行为实体
};
- (void)testBlockOne{
void(^myBlock)(void) = ^(void){
NSLog(@"This is one");
};
myBlock();
}
void(^myBlock)(void) = ^(void){
NSLog(@"This is one");
};
- (void)testBlockTwo{
void(^myBlock)(NSString *) = ^(NSString *str){
NSLog(@"str:%@", str);
};
myBlock(@"Thanks");
}
/**
* 待返回值NSString类型
*/
- (void)testBlockThree{
NSString*(^myBlock)(NSString *,NSInteger) = ^(NSString *str,NSInteger value){
NSLog(@"str:%@", str);
NSLog(@"result:%@", str);
return str;
};
myBlock(@"Thanks1", 123);
}
/**
* 带返回值int类型的Block
*/
- (void)testBlockFour{
int(^myBlock)(NSString *,NSInteger) = ^(NSString *str,NSInteger value){
NSLog(@"value:%d", value);
return value;
};
myBlock(@"hello", 123);
}
Block 回调:
//
// SecondViewController.h
// testBlockDemo1
//
// Created by Evan on 14-6-11.
// Copyright (c) 2014年 KK. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef void(^ColorBlock)(UIColor *color);
@interface SecondViewController : UIViewController
{
ColorBlock _changeColorBlock;
}
- (void)changeColorWithBlock:(ColorBlock)color;
@end
//
// SecondViewController.m
// testBlockDemo1
//
// Created by Evan on 14-6-11.
// Copyright (c) 2014年 KK. All rights reserved.
//
#import "SecondViewController.h"
@interface SecondViewController ()
@end
@implementation SecondViewController
-(void)buttonAction:(UIButton *)sender{
_changeColorBlock([UIColorredColor]);
[selfdismissViewControllerAnimated:YEScompletion:^{
}];
}
- (void)changeColorWithBlock:(ColorBlock)color{
_changeColorBlock = color; // 这里如果实在非arc的情况下 要进行 Block_copy 和Block_release
}
@end
//
// RootUIViewController.m
// testBlockDemo1
//
// Created by Evan on 14-6-11.
// Copyright (c) 2014年 KK. All rights reserved.
//
#import "RootUIViewController.h"
#import "SecondViewController.h"
@interface RootUIViewController ()
@end
@implementation RootUIViewController
-(void)buttonAction:(UIButton *)sender{
SecondViewController *secCtl = [[SecondViewControlleralloc]init];
[secCtl changeColorWithBlock:^(UIColor *color) {
self.view.backgroundColor = color;
}];
[selfpresentViewController:secCtlanimated:YEScompletion:^{
}];
}
@end