NSTimer 分配作为属性
如果我想创建一个具有三个实例变量和方法的简单类,
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
scheduledTimerWithTimeInterval
返回NSTimer
的实例。只需使用属性并覆盖设置器即可使计时器无效,您可以使用 self.timer 获得指向计时器的指针,并且当您设置 self.timer = newTimer 时,它会保留新的并使旧的无效并释放。
需要注意的是,您的 setter 期望输入计时器是自动释放的副本。如果您打算使用已经在使用的 NSTimer
scheduledTimerWithTimeInterval
方法,那么这就没问题。scheduledTimerWithTimeInterval
returns an instance ofNSTimer
. Just use properties and override the setter to invalidate the timerHer you have a pointer to the timer using
self.timer
, and when you setself.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.