gpt4 book ai didi

ios - 当我呈现另一个 View Controller 时,NSTimer 不会停止

转载 作者:行者123 更新时间:2023-11-29 05:23:29 25 4
gpt4 key购买 nike

我有一个 viewController1 设置计时器。
当计时器倒计时到 0 时,我将呈现 viewController2。
计时器也会继续运行,尽管我将计时器函数称为 invalidate
然后我标记当前的 View Controller 代码,它似乎正确停止。

//ViewController2 *vc = [[ViewController2 alloc] init];
//[self presentViewController:vc animated:false completion:nil];

代码有什么问题?

#import "ViewController.h"
#import <WebKit/WebKit.h>
#import "ViewController2.h"

@interface ViewController ()<WKScriptMessageHandler, WKNavigationDelegate,WKUIDelegate>

@property (nonatomic,strong) WKWebView* webView;
@property (nonatomic, strong) WKWebViewConfiguration * webConfig;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic) int count;

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:[self createWKWebApp]];
[self.view addSubview: self.webView];
[self.webView.configuration.preferences setValue:@YES forKey:@"allowFileAccessFromFileURLs"];
self.webView.scrollView.bounces = NO;
[self.webView setContentMode:UIViewContentModeScaleAspectFit];
self.webView.navigationDelegate = self;
self.webView.UIDelegate = self;

NSURL *url = [NSURL URLWithString:@"https://www.google.com.tw"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];

self.count = 5;

self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired) userInfo:nil repeats:YES];
}

-(void)timerFired {

NSLog(@"===) self.count : %d", self.count);

if (self.count == 0) {

ViewController2 *vc = [[ViewController2 alloc] init];
[self presentViewController:vc animated:false completion:^{
[self.timer invalidate];
self.timer = nil;
}];

} else {
self.count -= 1;
}

}


- (WKWebViewConfiguration *)createWKWebApp {
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
WKUserContentController *userContent = [[WKUserContentController alloc] init];

config.userContentController = userContent;

return config;
}

- (void)userContentController:(WKUserContentController*)userContentController didReceiveScriptMessage:(WKScriptMessage*)message {


}

@end

最佳答案

在呈现 ViewController 之前,停止计时器

[self.timer invalidate];
self.timer = nil;
ViewController2 *vc = [[ViewController2 alloc] init];
[self presentViewController:vc animated:false completion:nil];

关于ios - 当我呈现另一个 View Controller 时,NSTimer 不会停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58428511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com