#import "ViewController.h"
typedef void(^MyBlock)();
@interface ViewController ()
@property (nonatomic,copy) MyBlock block;
@property (nonatomic,copy) NSString *name;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
__weak typeof(self) weakself = self;
self.block = ^{
weakself.name = @"block";
};
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
關於block 循環引用 weakSelf
block代碼塊裏用到的東西,比如主線程裏的全局變量,局部變量,UI等,block都會對它指向一個strong指針。也就是說,局部變量所在的局部代碼運行完後,局部變量不會釋放,直到block消失,它才釋放。
這個不太好,這樣如果block代碼裏面有self.something,而block又存儲在strong的全局變量裏,會導致block對self一個strong指針,self對block又有一個strong指針,就導致了memory circle。相應的解決辦法是:
__weak MyClass *weakself = self;
使得block指向self一個弱指針。self指向block仍舊是強指針。這樣一個是弱的便解決問題了。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.