RootViewController.m
#import "RootViewController.h"
#import "SecondViewController.h"
@interface RootViewController ()
@end
@implementation RootViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
button.frame = CGRectMake(100, 100, 150, 50);
[self.view addSubview:button];
button.layer.borderWidth = 1;
[button setTitle:@"下一页" forState:UIControlStateNormal];
[button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
int (*p)(int, int) = maxValue;
NSLog(@"%d", p(10, 20));
}
- (void)click:(UIButton *)button {
1.等号左边:先写返回值类型,然后(),里面写^和block的名字,然后在()里写参数类型,把函数指针的*p变成^block.
2.等号右边:先以^开头,然后写形参列表,列表里的形参要和等号左边的形参类型和顺序相应,最后写函数部分.
3.注意有返回值的block一定要写return,在最后以分号结尾.
int (^block)(int, int) = ^(int a, int b) {
return 10;
};
NSLog(@"%d", block(10, 20));
void (^block)() = ^{
NSLog(@"1");
};
block();
void (^block)(float, float, float, float) = ^(float R, float G, float B, float A){
self.view.backgroundColor = [UIColor colorWithRed:R green:G blue:B alpha:A];
};
block(arc4random() % 256 / 255.0, arc4random() % 256 / 255.0, arc4random() % 256 / 255.0, 1);
SecondViewController *second = [[SecondViewController alloc] init];
[self.navigationController pushViewController:second animated:YES];
[second release];
1.写一个block,没有参数没有返回值,改变背景颜色.
void (^block)() = ^{
self.view.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255.0 green:arc4random() % 256 / 255.0 blue:arc4random() % 256 / 255.0 alpha:1];
};
2.传值,这次我们传一个block
second.block = block;
3.没有返回值,参数是一个字符串
void (^block)(NSString *) = ^(NSString *str) {
NSLog(@"%@", str);
};
second.block = block;
void (^block1)() = ^(){
};
NSLog(@"%p", block1);
int a = 10;
void (^block2)() = ^(){
NSLog(@"%d", a);
};
NSLog(@"%p", block2);
}
SecondViewController.h
#import <UIKit/UIKit.h>
typedef void(^Block)(NSString *);
@interface SecondViewController : UIViewController
@property(nonatomic, copy)Block block;
1.写一条属性,用来接收前一页的block.
@property(nonatomic, copy)void(^block)();
@end
SecondViewController.m
#import "SecondViewController.h"
@interface SecondViewController ()
@end
@implementation SecondViewController
- (void)dealloc
{
Block_release(_block);
[super dealloc];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
button.frame = CGRectMake(100, 100, 150, 50);
[self.view addSubview:button];
button.layer.borderWidth = 1;
[button setTitle:@"返回" forState:UIControlStateNormal];
[button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
}
- (void)click:(UIButton *)button {
[self.navigationController popToRootViewControllerAnimated:YES];
self.block();
self.block(@"哈哈");
}