【问题标题】:Can't trigger function from NSTimer's selector无法从 NSTimer 的选择器触发功能
【发布时间】:2013-10-28 02:18:02
【问题描述】:

这是我的代码:

- (IBAction)run:(id)sender {

    animationPointer = 0;

    self.animationArray = [[NSMutableArray alloc] init];


    UIView *allViews = [[UIView alloc]
        initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];

    for (int i = 0; i < [self.paths count]; i++) {

        [allViews addSubview:[self createAnimation:[self.paths objectAtIndex:i]]];

        [self.animationArray addObject:allViews];
    }

    timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(animateTurn)
        userInfo:nil repeats:YES];

}

- (void)animateTurn {
    UIView *tempView = [self.animationArray objectAtIndex:animationPointer];
    [self.view addSubview:tempView];
    for (UIImageView *view in tempView.subviews) {
        [[tempView.subviews objectAtIndex:animationPointer] startAnimating];
    }

    animationPointer++;

    if (animationPointer >= [self.animationArray count]) {
        [timer invalidate];
    }
}

createAnimation 如您所料,返回一个完全动画的UIImageView。计划是在每个UIView 上设置几个,然后在UIView 上为它们全部设置动画,然后在半秒后下一个并重复。目前每个UIView 上只有一个。

但是,在 NSTimer 上调用 animateTurn 时,动画不会显示。 如果我通过普通的[self animateTurn] 调用该方法,那么它们会出现,但NSTimerperformSelector 函数都没有。

对此有任何帮助(甚至是更好的方法的建议)?

编辑: 我应该提到该函数实际上正在被触发并且代码正在运行,包括 startAnimating(使用 BOOL/NSLog 检查)。根本没有显示任何内容。

【问题讨论】:

  • 您应该检查该方法是否在主线程上调用。

标签: ios objective-c animation nstimer


【解决方案1】:

这是你的解决方案:-

这是我使用的,现在选择器正在工作。 :-)

  if (![NSThread isMainThread]) 
    { [self performSelectorOnMainThread:@selector(selectorToRunInMainThread) withObject:nil waitUntilDone:NO]; 
     }
 -(void)selectorToRunInMainThread
{
 NSString *str = @"Timer event has fired"; 
NSTimer *atimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateModel:) userInfo:str repeats:YES]; 
} 

【讨论】:

  • 事情就是这样。首先,即使在选择器调用的方法中,[NSthread isMainThread] 也会返回 true...YET 使用 animateTurn 调用 performSelectorOnMainThread 设法使其工作...但是在将动画代码移动到另一个方法并再次使用 NStimer 调用它之后什么也没产生.发生了一些奇怪的事情。
【解决方案2】:

在你的计时器后面加上这一行:-

    [timer fire];

【讨论】:

  • 您能解释一下为什么这样做有效或应该做什么吗?这对我来说没有意义。
  • @imartin,您可以使用此方法触发重复计时器,而不会中断其常规触发时间表。如果计时器是非重复的,它会在触发后自动失效,即使它的预定触发日期尚未到来。供参考参考developer.apple.com/library/ios/DOCUMENTATION/Cocoa/Reference/…
  • @hussainShabbir 谢谢,但我了解-fire 的作用。问题是,计时器根本没有触发(我从问题中了解到),我不知道手动触发如何解决此类问题。
  • @imartin,你说得对,这不是根本原因,它只是修复。对于根本原因,我们需要分析方法,它正在哪个线程中执行:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
相关资源
最近更新 更多