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.
}