NSTimer 分配作为属性

发布于 2024-09-08 17:02:27 字数 636 浏览 0 评论 0原文

如果我想创建一个具有三个实例变量和方法的简单类,

    NSInteger seconds;
    NSInteger minutes;
    NSTimer *timer;


- (void)setMinutes:(NSInteger)m;
- (void)setSeconds:(NSInteger)s;
- (NSInteger)minutes;
- (NSInteger)seconds;

我想要的是初始化一个 NSTimer 对象并用这些分钟/秒进行倒计时。但我不确定如何初始化计时器,并在需要时释放它(如果我有多个计时器)。我知道如何使用该方法:

[NSTimer scheduledTimerWithTimeInterval:1.0
                                target:self 
                               selector:@selector(doTimer:)
                               userInfo:nil
                                repeats:YES];

我没有看到 NSTimer 需要“alloc”的示例,或者是否也需要释放它。

If I wanted to create a simple class that has three instance variables and methods like

    NSInteger seconds;
    NSInteger minutes;
    NSTimer *timer;


- (void)setMinutes:(NSInteger)m;
- (void)setSeconds:(NSInteger)s;
- (NSInteger)minutes;
- (NSInteger)seconds;

What I want is to initialize a NSTimer object and have it countdown with those minutes/seconds. But I'm not sure how to initialize the timer, and release it if I need to (in the event I had multiple timers going). I know how to use the method:

[NSTimer scheduledTimerWithTimeInterval:1.0
                                target:self 
                               selector:@selector(doTimer:)
                               userInfo:nil
                                repeats:YES];

I don't see an example of NSTimer needing "alloc", or if it needs to be released as well.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

护你周全 2024-09-15 17:02:27

scheduledTimerWithTimeInterval 返回 NSTimer 的实例。只需使用属性并覆盖设置器即可使计时器无效,

    NSTimer *timer;

@property (nonatomic, retain) NSTimer *timer;
- (void)setTimer:(NSTimer *)t;



- (void)setTimer:(NSTimer *)t {
    if (timer) {
        [timer invalidate];
        [timer release];
        timer = nil;
    }

    timer = [t retain];
}

您可以使用 self.timer 获得指向计时器的指针,并且当您设置 self.timer = newTimer 时,它会保留新的并使旧的无效并释放。

需要注意的是,您的 setter 期望输入计时器是自动释放的副本。如果您打算使用已经在使用的 NSTimer scheduledTimerWithTimeInterval 方法,那么这就没问题。

scheduledTimerWithTimeInterval returns an instance of NSTimer. Just use properties and override the setter to invalidate the timer

    NSTimer *timer;

@property (nonatomic, retain) NSTimer *timer;
- (void)setTimer:(NSTimer *)t;



- (void)setTimer:(NSTimer *)t {
    if (timer) {
        [timer invalidate];
        [timer release];
        timer = nil;
    }

    timer = [t retain];
}

Her you have a pointer to the timer using self.timer, and when you set self.timer = newTimer, it retains the new one and invalidates and releases the old one.

Important to note is that your setter expects the input timer to be an autoreleased copy. If you plan on using the NSTimer scheduledTimerWithTimeInterval method you are already using, this will be fine.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文