Have basically two view controllers oneviewcontroller and mainviewcontroller. In oneviewcontroller defined myTimer. In mainviewcontroller i m trying to pause and resume myTimer using UIButton. But getting message No Known class method for selector 'myTimer'
In OneViewController defined NSTimer as myTimer
#property (nonatomic, retain) NSTimer *myTimer;
#synthesize myTimer;
- (void)viewDidLoad {
[self myTimerMethod];
[super viewDidLoad];
}
- (void)myTimerMethod{
NSLog(#"myTimerMethod is Called");
myTimer = [NSTimer scheduledTimerWithTimeInterval:2.4
target:self
selector:#selector(updateView:)
userInfo:nil
repeats:YES];
}
- (void)updateView:(NSTimer *)theTimer
{
if (index < [textArray count])
{
self.textView.text = [self.textArray objectAtIndex:index];
self.imageView.image = [self.imagesArray objectAtIndex:index];
index++;
}else{
index = 0;
}
I m trying to pause and resume myTimer from mainviewcontroller
In mainviewcontroller.h
#class OneViewController;
#property (strong, nonatomic) OneViewController *oneviewcontroller;
#synthesize oneviewcontroller = _oneviewcontroller;
-(void)playpauseAction:(id)sender {
if([audioPlayer isPlaying])
{
[sender setImage:[UIImage imageNamed:#"music.png"] forState:UIControlStateNormal];
[audioPlayer pause];
[[OneViewController myTimer] invalidate]; **\\No Known class method for selector 'myTimer'**
}else{
[sender setImage:[UIImage imageNamed:#"audiostop.png"] forState:UIControlStateNormal];
[audioPlayer play];
[[OneViewController myTimer] fire]; **\\No Known class method for selector 'myTimer'**
if(isFirstTime == YES)
{
self.timer = [NSTimer scheduledTimerWithTimeInterval:06.0
target:self
selector:#selector(displayviewsAction:)
userInfo:nil
repeats:NO];
isFirstTime = NO; } } }
how can i fix this error.
Thanks for help.
Instead of [[OneViewController myTimer] invalidate]; use [self.oneviewcontroller.myTimer invalidate];
Also, in OneViewController implementation, instead of myTimer = [NSTimer scheduledTimerWithTimeInterval:..... use self.myTimer = [NSTimer scheduledTimerWithTimeInterval:.....
Related
So I have a view controller with a timer. It has one button. When the view loads for the very first time, the button should say "start."
When it is tapped, "start"->"pause".
Another tap, "pause"->"resume".
Another tap, "resume"->"pause".
Since I want the timer to be accurate, I detached it from the main thread (I think I chose the right method, I would appreciate some clarification). But it seems like detaching it from the thread actually calls the method...which makes the button start with "pause" instead of start. How do I fix this?
By the way, default value (loads with) for testTask.showButtonValue is 1.
- (void)viewDidLoad {
[super viewDidLoad];
[NSThread detachNewThreadSelector:#selector(startTimer:) toTarget:self withObject:nil];
if (testTask.showButtonValue == 1) {
[startButton setTitle:#"Start" forState:UIControlStateNormal];
} else if (testTask.showButtonValue == 2) {
[startButton setTitle:#"Pause" forState:UIControlStateNormal];
} else if (testTask.showButtonValue == 3){
[startButton setTitle:#"Resume" forState:UIControlStateNormal];
}
}
-(IBAction)startTimer:(id)sender{
if (testTask.showButtonValue == 1) {
[startButton setTitle:#"Pause" forState:UIControlStateNormal];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(timerAction:) userInfo:nil repeats:YES];
testTask.showButtonValue = 2;
} else if (testTask.showButtonValue == 2) {
[startButton setTitle:#"Resume" forState:UIControlStateNormal];
[timer invalidate];
timer = nil;
testTask.showButtonValue = 3;
} else if (testTask.showButtonValue == 3){
[startButton setTitle:#"Pause" forState:UIControlStateNormal];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(timerAction:) userInfo:nil repeats:YES];
testTask.showButtonValue = 2;
}
}
-(void)timerAction:(NSTimer *)t
{
if(testTask.timeInterval == 0)
{
if (self.timer)
{
[self timerExpired];
[self.timer invalidate];
self.timer = nil;
}
}
else
{
testTask.timeInterval--;
}
NSUInteger seconds = (NSUInteger)round(testTask.timeInterval);
NSString *string = [NSString stringWithFormat:#"%02u:%02u:%02u",
seconds / 3600, (seconds / 60) % 60, seconds % 60];
timerLabel.text = string;
NSLog(#"%f", testTask.timeInterval);
}
I suggest going about this in a different way:
#interface SNDViewController ()
#property (weak, nonatomic) IBOutlet UIButton *startButton;
#property (weak, nonatomic) IBOutlet UILabel *timerLabel;
#property (nonatomic, strong) NSTimer *timer;
#property (nonatomic, assign) NSTimeInterval accumulativeTime;
#property (nonatomic, assign) NSTimeInterval currentReferenceTime;
#end
#implementation SNDViewController
EDIT: when the view loads, initialise self.accumulativeTime and update the timer label. The initialisation of accumulativeTime variable should really be done in the appropriate init* method, e.g. initWithNibName:bundle:. It is at this point that you would read the timer value from core data.
- (void)viewDidLoad
{
[super viewDidLoad];
self.accumulativeTime = 300;
[self updateTimerLabelWithTotalTime:self.accumulativeTime];
}
- (IBAction)changeTimerState:(UIButton *)sender
{
if (self.timer == nil) {
self.currentReferenceTime = [NSDate timeIntervalSinceReferenceDate];
[self.timer invalidate];
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:#selector(updateTimer:) userInfo:nil repeats:YES];
} else {
//Pause the timer and track accumulative time.
NSTimeInterval now = [NSDate timeIntervalSinceReferenceDate];
[self.timer invalidate];
self.timer = nil;
NSTimeInterval timeSinceCurrentReference = now - self.currentReferenceTime;
EDIT: subtract timeSinceCurrentReference from accumalitiveTime, because this is a countdown timer. Also added a comment for saving to core data if necessary.
self.accumulativeTime -= timeSinceCurrentReference;
[self updateTimerLabelWithTotalTime:self.accumulativeTime];
//Optionally save self.accumulativeTime to core data for future use.
}
NSString *buttonTitle = (self.timer != nil) ? #"Pause" : #"Resume";
[self.startButton setTitle:buttonTitle forState:UIControlStateNormal];
}
You don't need to store any unnecessary state, such as the showButtonValue variable. Instead you can base your decision of whether to pause or resume on whether or not self.timer == nil. If there is no timer running, then grab the current reference time and start a new timer. The timer is scheduled to fire every 0.01 seconds, which will hopefully make it accurate to 0.1 seconds. You never need to change the button's title to "Start". It is either "Pause" or "Resume".
When the timer is paused by the user, we dispose of self.timer and update the timer label with the most accurate time.
- (void)updateTimer:(id)sender
{
NSTimeInterval now = [NSDate timeIntervalSinceReferenceDate];
NSTimeInterval timeSinceCurrentReference = now - self.currentReferenceTime;
EDIT: subtract timeSinceCurrentReference from self.accumulativeTime to get the totalTime (i.e. totalTime decreases as time goes by).
NSTimeInterval totalTime = self.accumulativeTime - timeSinceCurrentReference;
if (totalTime <= 0) {
totalTime = 0;
[self.timer invalidate];
self.timer = nil;
//What to do when we reach zero? For example, we could reset timer to 5 minutes:
self.accumulativeTime = 300;
totalTime = self.accumulativeTime;
[self.startButton setTitle:#"Start" forState:UIControlStateNormal];
}
[self updateTimerLabelWithTotalTime:totalTime];
}
Each time the timer is fired, we get the total time by finding the difference between now and self.currentReferenceTime and add it to self.accumulativeTime.
- (void)updateTimerLabelWithTotalTime:(NSTimeInterval)totalTime
{
NSInteger hours = totalTime / 3600;
NSInteger minutes = totalTime / 60;
NSInteger seconds = totalTime;
NSInteger fractions = totalTime * 10;
self.timerLabel.text = [NSString stringWithFormat:#"%02u:%02u:%02u.%01u", hours, minutes % 60, seconds % 60, fractions % 10];
}
#end
The method - (IBAction)changeTimerState:(UIButton *)sender is called by the UIButton on the "Touch Up Inside" event (UIControlEventTouchUpInside).
You don't need to do anything in viewDidLoad.
Also, and importantly, this is all done on the main thread. If anything gets in the way of the main thread updating the timer label, then the text visible to the user may be inaccurate, but when it is updated, you can be sure that it will be accurate again. It depends on what else your app is doing. But since all UI updates must be done on the main thread there is really no avoiding this.
Hope this helps. Let me know if anything is unclear.
(Xcode project available here: https://github.com/sdods3782/TVTTableViewTest)
Calling detachNewThreadSelector will create a new thread and perform the selector mentioned, immediately afer the call.
For fixing your issue change your methods like:
- (void)viewDidLoad
{
[super viewDidLoad];
[NSThread detachNewThreadSelector:#selector(startTimer:) toTarget:self withObject:nil];
}
-(IBAction)startTimer:(id)sender
{
if (testTask.showButtonValue == 1) {
[startButton setTitle:#"Start" forState:UIControlStateNormal];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(timerAction:) userInfo:nil repeats:YES];
testTask.showButtonValue = 3;
} else if (testTask.showButtonValue == 2) {
[startButton setTitle:#"Resume" forState:UIControlStateNormal];
[timer invalidate];
timer = nil;
testTask.showButtonValue = 3;
} else if (testTask.showButtonValue == 3){
[startButton setTitle:#"Pause" forState:UIControlStateNormal];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(timerAction:) userInfo:nil repeats:YES];
testTask.showButtonValue = 2;
}
}
myTimer is defined in OneViewController and i m trying to invalidate and fire it again from mainviewcontroller but it is not working. What exactly i m missing here.
here is my code
OneViewController.h
#property (nonatomic, strong) NSTimer *myTimer;
OneViewController.m
#synthesize myTimer;
- (void)viewDidLoad
{
[super viewDidLoad];
[self myTimerMethod];}
- (void)myTimerMethod{
NSLog(#"myTimerMethod is Called");
self.myTimer = [NSTimer scheduledTimerWithTimeInterval:2.4
target:self
selector:#selector(updateView:)
userInfo:nil
repeats:YES];
}
- (void)updateView:(NSTimer *)theTimer
{
if (index < [textArray count])
{
self.textView.text = [self.textArray objectAtIndex:index];
self.imageView.image = [self.imagesArray objectAtIndex:index];
index++;
}else{
index = 0;
}
}
MainViewController.h
#class OneViewController;
#property (strong, nonatomic) OneViewController *oneviewcontroller;
MainViewController.m
#synthesize oneviewcontroller = _oneviewcontroller;
-(void)playpauseAction:(id)sender {
if([audioPlayer isPlaying])
{
[sender setImage:[UIImage imageNamed:#"music.png"] forState:UIControlStateNormal];
[audioPlayer pause];
[self.oneviewcontroller.myTimer invalidate];
}else{
[sender setImage:[UIImage imageNamed:#"audiostop.png"] forState:UIControlStateNormal];
[audioPlayer play];
[self.oneviewcontroller.myTimer fire];
if(isFirstTime == YES)
{
self.timer = [NSTimer scheduledTimerWithTimeInterval:06.0
target:self
selector:#selector(displayviewsAction:)
userInfo:nil
repeats:NO];
isFirstTime = NO; } } }
- (void)displayviewsAction:(id)sender{
OneViewController *oneviewcontroller = [[OneViewController alloc] init];
oneviewcontroller.view.frame = CGRectMake(0, 0, 320, 430);
CATransition *transitionAnimation = [CATransition animation];
[transitionAnimation setDuration:1];
[transitionAnimation setType:kCATransitionFade];
[transitionAnimation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]];
[self.view.layer addAnimation:transitionAnimation forKey:kCATransitionFade];
[self.view addSubview:oneviewcontroller.view];
}
Appreciate help.
Thanks.
You create OneViewController as a local variable of the method displayviewsAction. Not as the property you defined previously.
That's why it's not working, the variable gets released once you exit the method.
Change this line:
OneViewController *oneviewcontroller = [[OneViewController alloc] init];
With this one:
self.oneviewcontroller = [[OneViewController alloc] init];
I want to set time count down like start with 60sec then elapsed 59,58,57 etc... this elapsed time show in bottom of the screen, How to set this?
Please help me
Thanks in Advance
You can use like:
Declare a NSTimer object on the #interface like NSTimer *aTimer;
-(void)viewDidLoad
{
aTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(elapsedTime) userInfo:nil repeats:YES];
}
-(void)elapsedTime
{
static int i = 60;
label.text = [NSString stringWithFormat:#"%d",i];
i--;
if(i<0)
{
[aTimer invalidate];
aTimer = nil;
}
}
Here label is a IBOutlet UILabel, that is set to interface.
You can do this with NSTimer see my example -
Declared
NSTimer *timer;
int count;
Globally in your ViewController.h class
Then you can start your count down in viewDidLoad: method.
- (void)viewDidLoad
{
//label is your **UILabel**
label.text = #"60";
count = 59;
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(countDown) userInfo:nil repeats:YES];
}
-(void)countDown
{
if(count > 0)
{
label.text = [[NSNumber numberWithInt:count] stringValue];
count --;
}
else
{
[timer invalidate];
}
}
This is my code
- (void)updateCounterImage:(NSTimer *)theTimer
{
static int count = 0;
count += 1;
int crb = 6 - count;
UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:#"ipad_game_timer_digit-%d.png", crb]];
if ( count == 6)
[timer release];
[countTime setImage:image];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
correctLevel.hidden = YES;
incorrectLevel.hidden = YES;
incorrectAnswer.hidden = YES;
correctAnswer.hidden = YES;
timer = [NSTimer scheduledTimerWithTimeInterval:1.0f
target:self
selector:#selector(updateCounterImage:)
userInfo:nil
repeats:NO];
}
#import <UIKit/UIKit.h>
#interface GameController : UIViewController
{
IBOutlet UIImageView *countTime;
NSTimer *timer;
}
#end
The problem is my imageView is not changing its image for countime.
You have set repeats to NO in the scheduledTimerWithTimeInterval which means the timer will only tick once.
You should write
timer = [NSTimer scheduledTimerWithTimeInterval:1.0f
target:self
selector:#selector(updateCounterImage:)
userInfo:nil
repeats:YES];
#interface ClassWithTimer : NSObject {
}
-(void) startTimer;
-(void) stopTimer;
#end
#implementation ClassWithTimer
NSTimer *up;
-(void) startTimer{
up = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(doSomething) userInfo:nil repeats:YES];
-(void) stopTimer{
[up invalidate];
}
- (void) doSomething{}
#end
then i do
- (IBAction)startTimers:(id)sender {
timer1 = [[ClassWithTimer alloc] initWithName:#"time1"];
timer2 = [[ClassWithTimer alloc] initWithName:#"time2"];
[timer1 startTimer];
[timer2 startTimer];
[timer1 stopTimer];
[timer2 stopTimer];
}
When i stop the timers i see that timer1 the same for timer2 and the invalidate method throw exception in [timer2 stopTimer] because this object invalidated at this moment.
I know that this is iOS policy but i can't find documentation for this.
Move
NSTimer *up;
into your .h file inside the interface block.
NSTimer needs to be an iVar, you are just declaring freely in the class allowing the two classes to share the same timer. Also you need to release the previous timer then retain the new one in startTimer.
#interface ClassWithTimer : NSObject {
NSTimer *up; //Declare iVar(instance variables) here
}
-(void) startTimer;
-(void) stopTimer;
#end
#implementation ClassWithTimer
-(void) startTimer{
[up invalidate];
[up release];
up = [[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(doSomething) userInfo:nil repeats:YES] retain];
-(void) stopTimer{
[up invalidate]; //Do these same this line
[up release]; //and this line in your dealloc
up = nil;
}
- (void) doSomething{}
#end