簡體   English   中英

當我展示另一個視圖控制器時,NSTimer 不會停止

[英]NSTimer don't stop when I present another viewcontroller

我有一個 viewController1 設置計時器。
當計時器倒計時到 0 時,我將呈現 viewController2。
計時器也繼續運行,雖然我稱計時器 function invalidate
然后我標記了當前的視圖控制器代碼,它似乎正確停止了。

//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];

使 viewWillDisappear 委托方法中的計時器無效,並在視圖再次出現時再次觸發。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM