gpt4 book ai didi

iphone - 释放 NSTimer 的正确方法?

转载 作者:太空狗 更新时间:2023-10-30 03:57:41 24 4
gpt4 key购买 nike

在我的 dealloc 方法中释放 NSTimer 的正确方法是什么?它是使用以下代码创建的?

-(void)mainTimerLoop {

mainTimer = [NSTimer scheduledTimerWithTimeInterval:1/10
target:self
selector:@selector(gameLoop)
userInfo:nil
repeats:YES];
}

谢谢

最佳答案

你这样做的方式,你永远不会点击dealloc。计时器保留其目标。在这种情况下,这意味着计时器保留了您。在它失效之前它不会释放你。由于您创建了计时器,因此您还必须在 dealloc 之前的某个时刻使它无效,因为计时器的保留将阻止您的对象被dealloced。

你有两个选择:

  • 找另一个地方使计时器无效( View 离开屏幕,应用程序正在终止,你有什么)
  • 将其他东西设置为计时器的目标。

以后者为例:

@interface GameLoopTimerTarget : NSObject {
id owner; /* not retained! */
}
- (id)initWithOwner:(id)owner;
- (void)timerDidFire:(NSTimer *)t;
@end

@implementation GameLoopTimerTarget
- (id)initWithOwner:(id)owner_ {
self = [super init];
if (!self) return nil;

owner = owner_;
return self;
}

- (void)timerDidFire:(NSTimer *)t {
#pragma unused (t)
[owner performSelector:@selector(gameLoop)];
}
@end

/* In your main object… */
/* assume synthesized:
@property (retain, NS_NONATOMIC_IPHONE_ONLY) GameLoopTimer *mainTimerTarget; */
- (void)mainTimerLoop {
self.mainTimerTarget = [[[GameLoopTimerTarget alloc] initWithOwner:self] autorelease];
mainTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0 target:self.mainTimerTarget selector:@selector(timerDidFire:) userInfo:nil repeats:YES];
}

- (void)dealloc {
/* other stuff */
[timer invalidate], timer = nil;
[mainTimerTarget release], mainTimerTarget = nil;
/* more stuff */
[super dealloc];
}

注意时间间隔是 1.0/10.0 - 这也可以写成 0.1,但不能写成 1/10,因为该除法将截断为 0.0

另请注意这是如何打破保留周期的:

  • 您和您的计时器都保留计时器目标。
  • 您在正常时间触发了 dealloc。
  • 然后您使计时器无效并释放计时器目标。
  • 然后释放定时器目标。

关于iphone - 释放 NSTimer 的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3971698/

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