// myBlockTest.h
#import <Foundation/Foundation.h>
typedef void (^CustomEvent)(NSString* str);
@interface myBlockTest : NSObject
-(void) testNormalBlock;
-(void) showMsg: (void (^)(NSString* str)) event;
-(void) showIndex: (NSInteger) index;
-(void) showCstEvent;
@property (strong,nonatomic) CustomEvent cst;
@end
// myBlockTest.m
#import "myBlockTest.h"
@implementation myBlockTest
#pragma mark - Block的普通使用
-(void) testNormalBlock
{
NSInteger n = 20;
static NSInteger sn = 40;
__block NSInteger bn = 50;
/*最普通的用法了吧,和lambda一样了*/
void (^NormalBlock1)(NSInteger) = ^(NSInteger avalue)
{
NSLog(@"%ld", avalue);
};
NormalBlock1(n);
/*注意上面返回void,定义部分没有写返回值,这也行。如果有呢,不写就错了
Incompatible block pointer types initializing 'int (^__strong)(NSInteger)' with an expression of type 'NSInteger (^)(NSInteger)'
两头加上返回值就可以了*/
NSInteger (^NormalBlock2)(NSInteger) = ^NSInteger(NSInteger avalue)
{
NSLog(@"%ld", avalue);
return avalue;
};
NormalBlock2(n);
/*注意,这个算是个坑了吧,静态的变量除外啊
在其主体中用到的outA这个变量值的时候做了一个copy的动作,把outA的值copy下来
这个说法我没理解,按照lambda的语法,这个应该是等于类型的,加上__block就是引用类型的了*/
void (^NormalBlock3)(NSInteger) = ^void(NSInteger avalue)
{
NSLog(@"%ld", n);//20
NSLog(@"%ld", sn);//60
};
n=30;
sn = 60;
NormalBlock3(n);
NSLog(@"%ld", n);//30
/*改变变量值呢?Variable is not assignable (missing __block type specifier)
得加关键字__block*/
void (^NormalBlock4)(NSInteger) = ^void(NSInteger avalue)
{
bn++;
NSLog(@"%ld", bn);//51
};
n=30;
NormalBlock4(bn);
/*先声明后定义的形式*/
void(^NormalBlock5)(NSInteger);
NormalBlock5 = ^void(NSInteger avlue)
{
NSLog(@"%ld", avlue);
};
/*定义两遍,应该用后者吧*/
NormalBlock5 = ^void(NSInteger avlue)
{
NSInteger nb = avlue * 2;
NSLog(@"%ld", nb);
};
NormalBlock5(25);
}
#pragma mark - 直接在函数的形参里面声明原型
-(void)showMsg:(void (^)(NSString * str))event
{
NSString* str = @"HelloWorld";
if (event) {
event(str);
}
}
-(void)showIndex:(NSInteger)index
{
void (^showEvent)(NSInteger) = ^(NSInteger aIndex)
{
NSLog(@"%ld", aIndex);
};
showEvent(index);
}
#pragma mark - 调用属性了,类似delphi的oncreate之类的
-(void)showCstEvent
{
NSString* str = @"HelloWorldEvent";
if (self.cst) {
self.cst(str);
}
}
@end
// ViewController.m
#import "ViewController.h"
#import "myBlockTest.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
myBlockTest* m = [[myBlockTest alloc] init];
[m showMsg:^(NSString *str) {
NSLog(@"%@",str);
}];
[m showIndex:5];
CustomEvent c = ^(NSString* str)
{
NSLog(@"%@",str);
};
m.cst = c;
[m showCstEvent];
if ([m respondsToSelector:@selector(showCstEvent)])
{
[m performSelector:@selector(showCstEvent)];
}
[m testNormalBlock];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end