iOS block分析

学习block从迷惑到渐渐的清晰,在这里跟大家分享一下

block的创建

block可以在函数内定义也可以在函数外定义
1.在文件范围内定义:
typedef void(^block名字)(block的参数,可以多个)
2.在函数内定义:
void(^myBlock)(NSString* str) = ^(NSString* str){ NSL(@"%@",str); };

block相当于一个匿名的函数,没有调用的话不会执行

__block的使用:

在block中引用外部变量的时候,其实是在没有运行时就捕捉到外部变量的值,当block内试图改变外部变量的值的时候,这时候编译器就提示x变量错误信息:Variable is not assigning (missing __block type);这时候在变量的声明是加__block就可以避免这种情况,如:__block NSString* name = @"张三";
通常block是用来跨越两个类来使用的,比如作为属性或者参数的话就可以跨越两个类使用了
比如在两个类之间相互传值:
假设需求:在一个rootViewController中点击跳转到另一个页面,在另一个页面NextViewController中的textFelix中填写后点击返回,将值传给rootViewController中的navigationItem.title
1.使用代理/协议实现

//在NextViewController.h中
//添加NextViewController的协议
@protocol NextViewControllerDelegate<NSObject>
@optional
-(void)nextViewControllerWithTitle:(NSString*)str;
@end
@interface NextViewController:UIViewController
@property(nonatomic,assign)id<NextViewControllerDelegate> delegate;
@end

//在NextViewController.m文件中
//在点击返回的按钮激发的方法中
-(void)pop{
if(self.delegate && [self.delegate respondsToSelector:@selector(nextViewControllerWithTitle:)]){
[self.delegate nextViewControllerWithTitle:self.textField.text];
}
[self.navigationController popViewControllerAnimated:YES];
}

在rootViewController中:

//导入NextViewController.h头文件

import “NextViewController.h”

//继承NextViewControllerDelegate协议
@interface rootViewController()<NextViewControllerDelegate>

@end
//在点击跳转的方法中
-(void)push{
NextViewController* nextVC = [[NextViewController alloc]init];
nextVC.delegate = self;
[self.navigationController pushViewController:nextVC animated:YES];
}
-(void)nextViewControllerWithTitle:(NSString*)str{
self.navigationItem.title = str;
}
2.使用block进行传值:

//在NextViewController.h中
@interface : UIViewController
@property(nonatomic,copy)void(^nextViewControllerBlock)(NSString* str);

@end

//NextViewController.m
//在返回函数中
-(void)pop{
if(self.nextViewControllerBlock){
self.nextViewControllrBlock(self.textField.text);
}
[self.navigationController popViewControllerAnimated:YES];
}

//rootViewController.m
//跳转函数中
-(void)push{
NextViewController* nextVC = [[NExtViewController alloc]init];
nextVC.nextViewControllerBlock = ^(NSString* str){
self.navigationItem.title = str;
};
}

使用block来传值比delegate要简洁的多,实际上,block就是用来代替Delegate的功能的

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,401评论 30 472
  • 前言 Blocks是C语言的扩充功能,而Apple 在OS X Snow Leopard 和 iOS 4中引入了这...
    小人不才阅读 9,164评论 0 23
  • 1,Search Bar 怎样去掉背景的颜色(storyboard里只能设置background颜色,可是发现cl...
    以德扶人阅读 7,593评论 2 50
  • 前不久,马云的第一家无人超市在杭州的街头开业了,24小时营业!使用手机淘宝或者支付宝扫码可直接进店,没有一个收银员...
    疯狂的小皮匠阅读 1,832评论 0 0
  • 转眼暑假已经第五周要结束了,时间飞逝! 小朋友一直跟我们过着比较有规律的生活吧,作息也跟保持良好。早上七点左右起床...
    athenaliang阅读 1,787评论 0 0

友情链接更多精彩内容