之前一直觉得block很复杂难写,界面传值的时候老是使用麻烦的委托代理协议来实现,后面看到一句话,之后自己总结了一下block的使用方法,写了一份block的我觉得基本涵盖了所有用法的案例代码吧,觉得用block很装X的,也是面试笔试的热点,不仅可以在界面来回传值,还可以使用block与服务器交互的。如各位有补充,请多海涵指教。下面发代码,3个文件,main.m,Person的.h.m文件
main方法中
#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc,const char * argv[]) {
@autoreleasepool {
//其实只要记住下面系统提供的inlineblock,基本上block的用法你就会了
//block也是变量
// 返回值 block名 参数列表 参数列表(带变量名的)
// <#returnType#>(^<#blockName#>)(<#parameterTypes#>) = ^(<#parameters#>) {
// <#statements#>
// };
//先来最简单的4个例子,后面以此顺序类推
//无参无返回值
void (^blk) () = ^(){
NSLog(@"aaaaaaa");
};
blk();
//有参无返回值
void (^blk1) (NSString *) = ^(NSString *str){
NSLog(@"%@", str);
};
blk1(@"bbbbbbbb");
//无参有返回值
int (^blk2) () = ^(){
return 1;
};
NSLog(@"%d", blk2());
//有参又返回值
int (^blk3) (int a,int b) = ^(int a,int b){
return a + b;
};
NSLog(@"%d", blk3(1,1));
NSLog(@"---------------------------");
//假如把block变量作为自定义UI类的属性,可以模仿实现委托代理协议的功能
Person *p1 = [[Personalloc] init];
p1.blk = ^(){
NSLog(@"1");
};
p1.blk1 = ^(int d){
NSLog(@"%d", d);
};
p1.blk2 = ^(){
return 3;
};
p1.blk3 = ^(int d){
return d;
};
[p1 displayBlock];
NSLog(@"---------------------------");
p1.blck = ^(){
NSLog(@"111111");
};
p1.blck1 = ^(int d){
NSLog(@"%d", d);
};
p1.blck2 = ^(){
return 3333333;
};
p1.blck3 = ^(int d){
return d;
};
//block当做方法参数
[p1 displayBlock2:p1.blckand:p1.blck1and:p1.blck2and:p1.blck3];
}
return 0;
}
Person类
#import <Foundation/Foundation.h>
//给block定义别名
typedef void (^Blck)();
typedef void (^Blck1)(int);
typedef int (^Blck2)();
typedef int (^Blck3)(int);
@interface Person : NSObject
//使用别名定义block
@property (nonatomic, copy) Blck blk;
@property (nonatomic, copy) Blck1 blk1;
@property (nonatomic, copy) Blck2 blk2;
@property (nonatomic, copy) Blck3 blk3;
//不适用别名定义block
@property (nonatomic, copy) void (^blck)();
@property (nonatomic, copy) void (^blck1)(int);
@property (nonatomic, copy) int (^blck2)();
@property (nonatomic, copy) int (^blck3)(int);
-(void)displayBlock;
//使用block作为方法参数
-(void)displayBlock2:(void(^)()) b and:(void(^)(int)) b1 and:(int(^)()) b2 and:(int(^)(int)) b3;
@end
#import "Person.h"
@implementation Person
-(void)displayBlock2:(void (^)())b and:(void (^)(int))b1 and:(int (^)())b2 and:(int (^)(int))b3{
b();
b1(222222);
NSLog(@"%d", b2(333333));
NSLog(@"%d", b3(44444));
}
-(void)displayBlock{
self.blk();
self.blk1(2);
NSLog(@"%d",self.blk2());
NSLog(@"%d",self.blk3(4));
}
@end