gpt4 book ai didi

ios - NSTimer 不会停止

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:54:25 25 4
gpt4 key购买 nike

     [self performSelectorInBackground:@selector(method) withObject:nil];

-(void)method
{
timer1 = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(getLastImageName1) userInfo:nil repeats:YES];
runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:timer1 forMode:NSRunLoopCommonModes];
[runLoop run];
}

-(void)viewdidunload
{
[timer1 invalidate];
timer1=nil;
}

我在 HomeViewController 中启动了 Timer 即使我无效了,它仍然在 OtherViewController 中运行。我的代码有什么问题?

最佳答案

首先,当您覆盖生命周期方法时,您应该包含对该方法的 super 版本的调用。

其次,Objective-C 区分大小写,因此即使您的应用程序甚至尝试调用生命周期,viewDidUnload,您的方法也永远不会被调用,因为这就是您的标题你的方法。

第三,viewDidUnload 在 iOS 6.0 中被弃用,此时根本不应该使用,除非您不遗余力地支持向后兼容性。它永远不会在 iOS 6.0 及更高版本中被调用。


如果您希望计时器在用户导航离开当前 View 时停止,您需要这样的东西:

- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];

if (timer1.isValid) {
[timer1 invalidate];
}
timer1 = nil;
}

如果您正在寻找其他东西,则需要详细说明您到底想要完成什么。


如果您正在处理 iOS 6.0 之前的项目,无论出于何种原因,您的方法未被调用的原因至少部分是因为拼写错误。同样,Objective-C 区分大小写。您的方法名称应拼写为 viewDidUnload


为了将来引用,问题不应该是“为什么我的计时器没有失效?”您应该首先使用断点或 NSLog 语句来确定您的方法 viewdidunload 是否会尝试使计时器无效甚至触发。当您发现它没有被调用时,搜索并询问“How come viewdidunload isn't called?”然后你会去解决大写问题,问题将(可能)仍然存在,所以做更多的研究。如果到最后,你还是想不通,作为最坏的情况,帖子的问题应该是“为什么没有调用 viewdidunload?”

关于ios - NSTimer 不会停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21234335/

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