Objective c 正在检查NSTimer是否已添加到nsrunlop
假设我正在代码中的某个位置创建NSTimer,稍后,我想将其添加到mainRunLoop,前提是之前没有添加它:Objective c 正在检查NSTimer是否已添加到nsrunlop,objective-c,cocoa,nstimer,nsrunloop,Objective C,Cocoa,Nstimer,Nsrunloop,假设我正在代码中的某个位置创建NSTimer,稍后,我想将其添加到mainRunLoop,前提是之前没有添加它: NSTimer* myTimer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(targetMetho
NSTimer* myTimer = [NSTimer timerWithTimeInterval:1.0f
target:self
selector:@selector(targetMethod:)
userInfo:nil
repeats:YES];
代码中的另一个位置:
if("my myTimer wasn't added to the mainRunLoop")
{
NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
[runLoop addTimer:myTimer forMode:NSDefaultRunLoopMode];
}
有办法检查吗?有;在实例变量中保留对它的引用,并检查非-nil:
@interface MyClass() {
NSTimer *_myTimer;
}
@end
...
if (!_myTimer)
{
_myTimer = [NSTimer timerWithTimeInterval:1.0f
target:self
selector:@selector(targetMethod:)
userInfo:nil
repeats:YES];
NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
[runLoop addTimer:_myTimer forMode:NSDefaultRunLoopMode];
}
试试这个:
CFRunLoopRef loopRef = [[NSRunLoop mainRunLoop] getCFRunLoop];
BOOL timerAdded = CFRunLoopContainsTimer(loopRef, (CFRunLoopTimerRef)myTimer ,kCFRunLoopDefaultMode);
创建计时器后,请检查
timeraded
variable,\u myTimer!=无代码中有两个地方,稍后我想将其添加到运行循环中。但我只想添加一次。添加到同一个运行循环?是的-添加到同一个运行循环。然后我的答案就行了;您知道,一旦创建了它,它就会立即添加到runloop中。如果要将其从运行循环中删除,请同时使\u myTimer
无效,并将其设置为nil
,然后可以重新添加。我总是这样做的:如果该对象存在,则将其附加。无需保留已创建但未运行的计时器。