// ModalViewController.h
#import <UIKit/UIKit.h>
@interface ModalViewController : UIViewController
@end
// ModalViewController.m
#import "ModalViewController.h"
@interface ModalViewController ()
@property (nonatomic ,strong) void(^block)();
@end
@implementation ModalViewController
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)dealloc
{
NSLog(@"%@對象銷毀",self);
}
/**
* 說明,如果_block里面保存的代碼只是在主線程執(zhí)行腮敌,而且內(nèi)部保存的代碼用到外界的self
那么,必須得__weak typeof(self) weakSelf = self;然后用weakSelf變量就可以了氨鹏,
放在循環(huán)引用,
如果保存的代碼還得在子線程或者主線程延時之后做一些操作的話,還得用到self的話嫉嘀,首先第一步是
__weak typeof(self) weakSelf = self;第二步在保存的代碼位置寫__strong typeof(weakSelf) strongSelf = weakSelf;然后用strongSelf變量就可以了
*/
- (void)viewDidLoad {
[super viewDidLoad];
int a = 0;
// Block循環(huán)引用,跟block調(diào)用沒有關系
// block只要訪問外部強指針對象變量,就會對這個變量進行強引用.
__weak typeof(self) weakSelf = self;
_block = ^{
__strong typeof(weakSelf) strongSelf = weakSelf;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"延遲打印%@",strongSelf);
});
};
_block();
}
@end
// ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
// ViewController.m
#import "ViewController.h"
#import "ModalViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
ModalViewController *modalVc = [[ModalViewController alloc] init];
modalVc.view.backgroundColor = [UIColor redColor];
[self presentViewController:modalVc animated:YES completion:nil];
}
- (void)viewDidLoad {
[super viewDidLoad];
}
@end
最后編輯于 :
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者