0
- (void)start{
    NSTimer *mtimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(scheduleSomeNSTimer:) userInfo:nil repeats:YES];
}

- (void)scheduleSomeNSTimer:(NSTimer *)timer{
    NSTimer *newtimer = [NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:@selector(showAction:) userInfo:nil repeats:NO];
}

- (void)showAction:(NSTimer *)timer{
    NSLog(@"action show!");
}

如果我想使按功能调度的 nstimer 之一无效-(void)addSomeNSTimer:(NSTimer *)timer

应用程序将重复创建 newtimer,所以当我需要使这些 newnstimer 之一无效时,我怎样才能找到我需要的对象

例如:应用程序创建 4 个 nstimer 并循环运行我如何找到其中一个并使之无效

4

5 回答 5

2

您应该在课堂上保留对计时器的引用并执行以下操作:

self.myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(scheduleSomeNSTimer:) userInfo:nil repeats:YES];

因此,每当您想使其无效时,只需执行以下操作:

[self.myTimer invalidate];

于 2011-09-19T07:45:35.850 回答
1

To_play是 NSTimer 对象。

[To_play invalidate];
于 2011-09-19T07:42:29.610 回答
1

您可以通过以下方式实现此目的:

根据您的反馈,请查看以下答案。

在 .h 文件中,在 Array 上声明:

NSMutableArray *arrTimers;

在 .m 文件中,在此数组中添加计时器,无论您何时创建计时器。

NSTimer *mtimer = [[NSTimer alloc] init];

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

[arrTimers addObject:mtimer];

然后你可以像下面这样使其无效:

NSTimer *myTimer = (NSTimer *)[arrTimers objectAtIndex:1];
if(myTimer != nil)
    {
        [myTimer invalidate];
        myTimer = nil;
    }

我希望它能解决你的问题。


if(timer == mtimer)
{

   if(mtimer != nil)
   {
        [mtimer invalidate];
        mtimer = nil;
   }
}

if(timer == newtimer)
{
    if(newtimer != nil)
    {
        [newtimer invalidate];
        newtimer = nil;
    }
}

干杯。

于 2011-09-19T07:46:25.237 回答
0

您可以在不保留对计时器的引用的情况下执行此操作。改为使用标志。

@property(nonatomic, assign) BOOL invalidateTimer; 

Timer相关的源码:

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

- (void)scheduleSomeNSTimer:(NSTimer *)timer
{
   if(YES == invalidateTimer)
   {
     if([timer isValid])
     {
       [timer invalidate];
       timer = nil;
     }
   }
}
于 2013-12-19T04:06:22.537 回答
0

声明一个 NSMutableArray 并在您的 scheduleSomeNSTimer 方法中,将 newtimer 对象添加到数组中。当您使此数组中的计时器对象无效时,您还需要将其从数组中删除。

于 2011-09-19T11:08:00.010 回答