gpt4 book ai didi

objective-c - NSTimer 在 UIView 中禁用 dealloc

转载 作者:太空狗 更新时间:2023-10-30 03:27:08 28 4
gpt4 key购买 nike

@interface someview:UIView{
NSTimer* timer;
}
@end

@implementation someview

-(void)dealloc{
NSLog(@"dealloc someview");
[timer invalidate];
timer = nil;
}
-(void)runTimer{
//
}
-(void)someMethod{

timer = [NSTimer timerWithTimeInterval:2.0f target:self selector:@selector(runTimer) userInfo:nil repeats:YES];
}

@end

释放 someview 不会调用 dealloc 并且计时器会继续运行。

如果我注释掉“timer = [NSTimer schedule...”部分,将调用 dealloc。这意味着我的代码的所有其他部分都正常工作,而计时器是罪魁祸首。 runTimer 方法是空的,这意味着它只是在搞乱我的计时器。

最佳答案

我认为在 UIView 内部使用 NSTimer 时最好的解决方案是覆盖 removeFromSuperview 方法;

- (void)removeFromSuperview
{
[timer invalidate];
timer = nil;

[super removeFromSuperview];
}

这里唯一要记住的是,您需要确保计时器不是 nil 对象,因为 removeFromSuperview 也可以从其他 UIView 的 super dealloc 方法自动调用。您可以包含条件以进行检查。

关于objective-c - NSTimer 在 UIView 中禁用 dealloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5670431/

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