NSTimer 触发时导致“无法识别的选择器”崩溃

2024-01-12

我正在使用一个NSTimer运行动画(现在只需调用它myMethod)。然而,它导致了崩溃。

这是代码:

@implementation SecondViewController


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.


- (void) myMethod
{
    NSLog(@"Mark Timer Fire");

}


- (void)viewDidLoad
{ 
[super viewDidLoad];



NSLog(@"We've loaded scan");

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

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


}

这是崩溃期间的输出

-[SecondViewController myMethod:]:无法识别的选择器发送到实例 0x4b2ca40 2012-06-21 12:19:53.297 测谎仪[38912:207]*由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[SecondViewController myMethod:]:无法识别的选择器发送到实例 0x4b2ca40”

那么我在这里做错了什么?


我在使用 Swift 时遇到了这个问题。可能不太明显的是,在 Swift 中我发现 NSTimer 的目标对象必须是 NSObject。

class Timer : NSObject {
   init () { super.init() }
   func schedule() {
      NSTimer.scheduledTimerWithTimeInterval(2.0,
                             target: self,
                             selector: "myMethod",
                             userInfo: nil,
                            repeats: true)
  }
  func myMethod() {
     ...
  }
}

希望这对某人有帮助。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

NSTimer 触发时导致“无法识别的选择器”崩溃 的相关文章

随机推荐