Im making a class that creates a timer that then calls a void using @selector or (SEL). The app crashes when [mytimer timer…]; is called because “unknown selector called”. The error is that it isnt finding the void I’m giving to it but i know that the void works fine. My question is how to I write the myselector part correctly?
+ (void) timer:(NSTimer*)timer interval:(int)interval selector:(SEL)myselector
{
timer = [NSTimer scheduledTimerWithTimeInterval:interval
target:self
selector:myselector
userInfo:nil
repeats:YES];
}
This is the method being implemented:
[mytimer timer:NameOfTimerTheWorks interval:0.1 selector:@selector(myVoid)];
...
- (void)myVoid
{
Do stuff
}
Also I understand that this class looks completely useless but there is more to it that I didnt include. My problem revolves around the selector.
There’s nothing wrong with your use of @selector(), your issue is with Objective C classes, and what
selfmeans in different scopes.The problem is that you’re creating your timer in a class
+method andselfat that point is not the instance you want, it’s actually theClassitself. I wouldn’t be doing it in a class method, but if you must, just pass in the reference to the target and it should send th message your’e expecting.Change your implementation to the following so you pass in the target, and return the timer
Additionally, in Objective C the standard way to name classes is with a capital letter, and camel case where appropriate. Your class should be
MyTimerand notmytimerand iVars are lowercase egnameOfTimerTheWorks.