iOS Block的使用

直接上代码:

#import <UIKit/UIKit.h>

#import "SecondViewController.h"

@interface RootViewController : UIViewController

@end

#import "RootViewController.h"

@interface RootViewController ()

@end

@implementation RootViewController

- (void)viewDidLoad {

   [super viewDidLoad];

   // 无参数 无返回值的block 打印一条语句

   void(^myBlock)() = ^void{

      NSLog(@"11");

   };

   myBlock();

   // 有参数 有返回值  两个整数相加

   int (^sum) (int,int) = ^(int a, int b){

      return a + b;

   };

   int s = sum(1,2);

   NSLog(@"%d",s);

   UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

   button.frame = CGRectMake(20, 100, 100, 50);

   [button setTitle:@"点我呀" forState:UIControlStateNormal];

   button.backgroundColor = [UIColor magentaColor];

   [button addTarget:self action:@selector(jumpTo:) forControlEvents:UIControlEventTouchUpInside];

   [self.view addSubview: button];

}

- (void)jumpTo:(UIButton *)button

{

   SecondViewController *second = [[SecondViewController alloc] init];

   //接收Block回调的值

   second.sendMessage = ^(NSString *name,NSString *address){

      //()里面的两个参数 就是传回来的值

      NSLog(@"%@",name);

      //修改按钮上的文字

      //会造成引用计数加1

      __block UIButton *tempButton = button;//避免造成引用计数加1的方式

      [tempButton setTitle:name forState:UIControlStateNormal];

   };

   [self.navigationController pushViewController:second animated:YES];

}

- (void)didReceiveMemoryWarning {

   [super didReceiveMemoryWarning];

   // Dispose of any resources that can be recreated.

}

@end

//***********************************************************************//

#import <UIKit/UIKit.h>

@interface SecondViewController : UIViewController

#pragma mark --Block属性 copy修饰 block本身会在栈区  copy是它存在堆区 安全操作)

@property(nonatomic,copy)void(^sendMessage)(NSString *name,NSString *address);

@end

#import "SecondViewController.h"

@interface SecondViewController ()

@end

@implementation SecondViewController

- (void)viewDidLoad {

   [super viewDidLoad];

   self.view.backgroundColor = [UIColor whiteColor];

   self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(backTo)];

}

- (void)backTo

{

   self.sendMessage(@"尼玛傻B二百五",@"屌丝");

   [self.navigationController popViewControllerAnimated:YES];

}

- (void)didReceiveMemoryWarning {

   [super didReceiveMemoryWarning];

   // Dispose of any resources that can be recreated.

}

@end




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值