NSTimer在启动时会导致“无法识别的select器”崩溃
我正在使用NSTimer
运行一个animation(现在只是称之为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:]:无法识别的select发送到实例0x4b2ca40 2012-06-21 12:19:53.297检测器[38912:207] *终止应用程序由于未捕获exception'NSInvalidArgumentException',原因:' – [SecondViewController myMethod:] :无法识别的select器发送到实例0x4b2ca40'
那么我在这里做错了什么?
要么你只能使用
- (void)myMethod: (id)sender { // Do things }
或者你可以做(删除:从两个方法的名称)..
animationTimer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(myMethod) userInfo:nil repeats: YES];
希望对你有帮助
我在使用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() { ... } }
希望这有助于某人。
取代这个
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(myMethod:) userInfo:nil repeats:YES];
这样
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(myMethod) userInfo:nil repeats:YES];
计时器的动作方法应该有一个参数 :
- (void)myMethod: (NSTimer *)tim { // Do things }
这个方法的名字是myMethod:
包括冒号。 您当前的方法的名称是myMethod
, 不带冒号,但是您通过传递具有该方法的名称来创build计时器: selector:@selector(myMethod:)
。
目前,定时器发送消息myMethod:
到你的对象; 你的对象不响应(但会响应myMethod
)并引发exception。