block可以造成循环引用,导致对象不能释放,造成内存泄露。
所以在使用的时候,要用__block 来对变量或属性进行修饰。
而且block的释放跟一般的变量不一样
布局为一个根视图控制器,一个firstViewcontroller。这里仅显示了firstViewcontroller的代码
#import "FirstViewController.h"
typedef void(^BLOCK)(NSString *);
@interface FirstViewController ()
{
UILabel *label;
}
@property(nonatomic,copy)BLOCK block;
@end
@implementation FirstViewController
- (void)dealloc
{
#pragma mark-----------------block的释放跟变量不一样
Block_release(_block);
[super dealloc];
}
- (void)viewDidLoad {
[super viewDidLoad];
label = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
self.view.backgroundColor = [UIColor cyanColor];
NSLog(@"++++++%lu",[_block retainCount]);
NSLog(@"-------%lu",self.retainCount);
__block FirstViewController *firstVC = self;
//在block中如果用到了self或者当前类的实例变量,一定要记得用__block修饰,否则会造成循环引用。
self.block = ^void(NSString *text){
firstVC.title = text;
};
NSLog(@"++++++%lu",[_block retainCount]);
NSLog(@"-------%lu",self.retainCount);
_block(@"First");
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}