接着上一遍,这里首先讲一下
block的反向传值
ViewController和ViewController1
//ViewController1里面
typedef void(^MyBlock)(NSString *str);
@interface ViewController1 : UIViewController
@property (nonatomic,copy) MyBlock myBlock;
ViewController里面的代码
//1.不会循环引用
ViewController1 *vc = [[ViewController1 alloc]init];
vc.myBlock = ^(NSString *str) {
NSLog(@"%@",str);
NSLog(@"%@",self.str);
NSLog(@"%@",self.str = str);
};
[self.navigationController pushViewController:vc animated:YES];
//ViewController1 里面进行反向传值
if (self.myBlock) {
self.myBlock(@"20");
}
[self.navigationController popViewControllerAnimated:NO];
//2.会循环引用
ViewController1 *vc = [[ViewController1 alloc]init];
vc.myBlock = ^(NSString *str) {
NSLog(@"%@",vc.VC1Str);
NSLog(@"%@",vc);
};
[self.navigationController pushViewController:vc animated:YES];
//3.解除循环引用
ViewController1 *vc = [[ViewController1 alloc]init];
__weak typeof(vc) weakSelf = vc;
vc.myBlock = ^(NSString *str) {
NSLog(@"%@",weakSelf.VC1Str);
NSLog(@"%@",weakSelf);
};
[self.navigationController pushViewController:vc animated:YES];
block作为参数使用
这种只能在方法内部进行调用,用于回调和传值等
//这里声明了一个Person,里面有一个方法
typedef void (^Block) (NSString * str);
@interface Person : NSObject
-(void)testBlock:(Block)myBlock;
//在ViewController里面倒入一下
@interface ViewController ()
@property (nonatomic,strong)Person *person;
[self.person testBlock:^(NSString *str) {
NSLog(@"%@",str);
NSLog(@"%@",self.str);
NSLog(@"%@",self.str = str);
NSLog(@"%@",self.person.personStr);
}];
//像这种block是在方法中 ,以上在block里面的操作,都不会造成循环引用。这种block不属于对象的属性,并没有被对象持有,也并不会引起循环引用。
//AFNetworking里面也是这种操作,很多时候我们也会去这样使用。
block的注意点
1.在block内部使用外部指针且会造成循环引用情况下,需要用到_weak修饰外部指针
__weak typeof(self) weakSelf = self;
2.在block内部如果调用了延时函数还使用了弱指针会取不到指针,因为已经被销毁了,需要在block内部再将弱指针重新强引用一下。
__strong typeof(self) strongSelf = weakSelf;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[... test];
});
3.如果需要在block内部改变外部栈区变量的话,需要在用__block修饰外部变量
以上就是全部了,感觉有用的上个星,附上demo下载地址
如有疑问,欢迎跟我沟通,qq:2877025939