iOS Block的基本使用以及Block传值
2017-11-29 本文已影响10438人
Damen_9527
pragma mark About Block
//block的原型:
NSString *(^myBlock)(int);
//上面的代码声明了一个block(^)原型,名字叫做myBlock,包含一个int型的参数,返回值为NSString类型的指针。
//block的定义:
myBlock=^(int paramA){
return [NSString stringWithFormat:@"Passed number:%d",paramA];
};
myBlock(2);
pragma mark e.g. Block Create And Usage
//基本使用 返回值 UIImage object
UIImage *oldImage=[UIImage imageNamed:@"avatar"];
UIImage *(^myImageBlock)(UIImage*)=^(UIImage *image){
return image;
};
UIImage *newImage=myImageBlock(oldImage);
//基本使用 无返回值
NSString *string=@"";
void (^logBlock)(NSString *)=^(NSString *paramStr){
NSLog(@"logBlock log:%@",paramStr);
};
logBlock(string);
//含有block参数的函数 比较常见的类型,如网络请求中的successfulBlock
//方法
- (void)turnNumberWithNumberA:(NSInteger)a NumberB:(NSInteger)b andMyBlock:(void(^)(int aa,int bb))myBlock{
int c=[[NSNumber numberWithInteger:a]intValue];
int d=[[NSNumber numberWithInteger:b]intValue];
myBlock(c,d);
}
//调用
[self turnNumberWithNumberA:1 NumberB:2 andMyBlock:^(int aa, int bb) {
NSLog(@"aa is %d",aa);
NSLog(@"bb is %d",bb);
}];
//block在两个视图的传值 Apush到B B消失时将textfield的值传回A
//B.h
typedef void (^ReturnTextBlock)(NSString *showText);//给block重命名,方便调用
@interface B : UIViewController
@property (nonatomic, copy) ReturnTextBlock returnTextBlock;//声明一个block属性
- (void)returnText:(ReturnTextBlock)block;//加上后方便第A视图书写该block方法
@end
//B.m
- (void)returnText:(ReturnTextBlock)block {//block的实现方法
self.returnTextBlock = block;
}
- (void)viewWillDisappear:(BOOL)animated {
if (self.returnTextBlock != nil) {
self.returnTextBlock(self.inputTF.text);//视图将要消失时候调用
}
}
//A.m需要push的时候调用
B *bVC = [[B alloc]init];
[bVC returnText:^(NSString *showText) {//定义B视图后调用block
self.showLabel.text = showText;
}];
转载:http://blog.csdn.net/scott_cc/article/details/51152145
https://www.cnblogs.com/linzhengbo/p/5617602.html
http://blog.csdn.net/ysy441088327/article/details/7942928
http://www.jianshu.com/p/e03292674e60
http://www.jianshu.com/p/8696d78f88cf