Reputation: 349
I'm using a NSTimer
to run an animation (for now just call it myMethod
). However, its causing a crash.
Here's the code:
@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];
}
And here's the output during the crash
-[SecondViewController myMethod:]: unrecognized selector sent to instance 0x4b2ca40 2012-06-21 12:19:53.297 Lie Detector[38912:207] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[SecondViewController myMethod:]: unrecognized selector sent to instance 0x4b2ca40'
So what am I doing wrong here?
Upvotes: 3
Views: 5996
Reputation: 397
I ran into this problem while using Swift. It may not be evident that in Swift I discovered that the target object of NSTimer must be an NSObject.
class Timer : NSObject {
init () { super.init() }
func schedule() {
NSTimer.scheduledTimerWithTimeInterval(2.0,
target: self,
selector: "myMethod",
userInfo: nil,
repeats: true)
}
func myMethod() {
...
}
}
Hope this helps somebody.
Upvotes: 5
Reputation: 64012
The timer's action method should take one argument:
- (void)myMethod: (NSTimer *)tim
{
// Do things
}
The name of this method is myMethod:
, including the colon. Your current method's name is myMethod
, without the colon, but you create your timer by passing a method name that has it: selector:@selector(myMethod:)
.
Currently, then, the timer sends the message myMethod:
to your object; your object doesn't respond to that (but would respond to myMethod
) and raises an exception.
Upvotes: 2
Reputation: 2253
either you can use only
- (void)myMethod: (id)sender
{
// Do things
}
or you can do (remove : from both the method name)..
animationTimer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(myMethod) userInfo:nil repeats: YES];
hope this will help you
Upvotes: 4
Reputation: 1271
replace this
[NSTimer scheduledTimerWithTimeInterval:2.0
target:self
selector:@selector(myMethod:)
userInfo:nil
repeats:YES];
by this
[NSTimer scheduledTimerWithTimeInterval:2.0
target:self
selector:@selector(myMethod)
userInfo:nil
repeats:YES];
Upvotes: 3