NSTimer shows UILabel and UIImageView when it stops - xcode

In my app project I want to be able to tap a button, wait 5 seconds, and then a UILabel and UIImageView appear. Here's what I have so far:
- (IBAction)startTimer
{
responseBox.placeholder = #"Message Here";
timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:#selector(timerStop) userInfo:nil repeats:YES];
mainInt +=1;
}
- (void)timerStop
{
if (mainInt == 5)
{
[timer invalidate];
titleLabel.hidden = NO;
messageLabel.hidden = NO;
messageLabel.text = #"Message";
image.hidden = NO;
}
}
Everything's linked correctly, what's going on?

mainInt is only incremented when you press the startTimer button, so that does you no good in timerStop. Also, if you want to increment mainInt correctly, use mainInt++;
Try this:
- (IBAction)startTimer
{
responseBox.placeholder = #"Message Here";
timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:#selector(timerStop) userInfo:nil repeats:YES];
mainInt++;
}
- (void)timerStop
{
[timer invalidate];
titleLabel.hidden = NO;
messageLabel.hidden = NO;
messageLabel.text = #"Message";
image.hidden = NO;
}

Related

Pause and Resume Time Xcode

I know that there is no way to pause a timer using NSTimer. I know i have to store the date and call it again. I have tried every solution and i cannot find any that have successfully worked. So my question is, does anyone know how to pause and resume?
This worked good for me.
Created 2 UIButtons ('startButton' & 'resetButton'), a UILabel to display time ('timeLabel'), NSTimeInterval ('pauseTimeInterval'), NSTimer (stopWatchTimer') and used the following code:
NSDate *pauseStart, *previousFireDate, *startDate;
NSTimeInterval pauseTimeInterval;
NSTimer *stopWatchTimer;
-(void)pauseTimer{
pauseStart = [NSDate dateWithTimeIntervalSinceNow:0];
previousFireDate = [self fireDate];
[self setFireDate:[NSDate distantFuture]];
}
-(void)resumeTimer{
float pauseTime = -1*[pauseStart timeIntervalSinceNow];
[self setFireDate:[previousFireDate initWithTimeInterval:pauseTime sinceDate:previousFireDate]];
}
-(IBAction)startTime:(id)sender {
//start timer
if ([startButton.titleLabel.text isEqualToString:#"Start"] && (![self.stopWatchTimer isValid]) && ([timeLabel.text isEqualToString:#"00:00:00"]))
{
[startButton setTitle:#"Stop" forState:UIControlStateNormal];
startDate = [NSDate date];
startDate = [startDate dateByAddingTimeInterval:((-1)*(pauseTimeInterval))];
self.stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0
target:self
selector:#selector(updateTimer)
userInfo:nil
repeats:YES];
resetButton.hidden = YES;
}
//pause timer
else if (([self.stopWatchTimer isValid]) && ([startButton.titleLabel.text isEqualToString:#"Stop"]))
{
[startButton setTitle:#"Resume" forState:UIControlStateNormal];
[self.stopWatchTimer pauseTimer];
resetButton.hidden = NO;
}
//resume timer
else {
[startButton setTitle:#"Stop" forState:UIControlStateNormal];
startDate = [NSDate date];
startDate = [startDate dateByAddingTimeInterval:((-1)*(pauseTimeInterval))];
[self.stopWatchTimer resumeTimer];
resetButton.hidden = YES;
}
}
-(IBAction)resetTime:(id)sender {
[self.stopWatchTimer invalidate];
self.stopWatchTimer = nil;
self.timeLabel.text = #"00:00:00";
[startButton setTitle:#"Start" forState:UIControlStateNormal];
pauseTimeInterval = 0.0;
resetButton.hidden = YES;
}
-(void)updateTimer
{
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *timeString=[dateFormatter stringFromDate:timerDate];
self.timeLabel.text = timeString;
pauseTimeInterval = timeInterval;
}

how to stop runaway flashing NSButton / NSTimer (IOS or OSX ok)

I'm trying to make an NSButton (but I could use the technique for iOS too, so any answers are welcome).
I have a button where hiding/enabling is turned on and off:
-(void)textDidChange:(NSNotification *)notification
{
timerStatus = 0;
timerTest = [NSTimer scheduledTimerWithTimeInterval:2.0
target:self
selector:#selector(changeButtonState:)
userInfo:nil
repeats:YES];
}
-(void) changeButtonState:(id) sender {
NSLog(#"%s", __FUNCTION__);
if (timerStatus == 2) return;
if (timerStatus == 0) {
timerStatus = 1;
saveButton.enabled = YES;
saveButton.hidden = NO;
} else {
timerStatus = 0;
saveButton.enabled = NO;
saveButton.hidden = YES;
}
}
The button blinks ok, but after it's associated method is fired (in this case a save action), I want the timer to stop and the button to stop blinking. It's this last part that's giving me a headache.. Any help appreciated.
- (IBAction)saveItemNotes:(id)sender
{
NSLog(#"%s", __FUNCTION__);
<do my save stuff here>
timerStatus = 2;
[timerTest invalidate];
timerTest = nil;
}
Just invalidate your timer in that same method where you change the button state.
Better yet, don't do it this way.
Use Core Animation instead if you want to draw attention to an interface item.

NSTimer is not firing the scheduled method

My code is given below.I am trying to show a counter on the screen in a window and enable a button after count limit is over.
When I run the code before nstimer and after nstimer are printed only once and nothing is printed from the time countdown function.Someone pelase help me.
- (void)startTimer:(NSInteger)count;
{
NSLog(#"Entered the start timer function");
self.countLimit = count;
[self.lbCount setStringValue:[NSString stringWithFormat:#"%ld",self.countLimit]];
NSLog(#"Before nstimer");
#try{
self.timeCounter = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(timeCountDown) userInfo:nil repeats:YES];
}
#catch (NSException* e) {
NSLog(#"%#",[e description]);
}
NSLog(#"After nstimer");
}
- (void)timeCountDown
{
NSlog(#"Entered the function");
self.countLimit = self.countLimit - 1;
NSLog(#"Just entered the function time countdown");
if (self.countLimit < 0) {
NSLog(#"Entered count limit less than 0");
[self.timeCounter invalidate];
self.timeCounter = nil;
[self.btContinue setEnabled:YES];
return;
}
[self.lbCount setStringValue:[NSString stringWithFormat:#"%ld",self.countLimit]];
}
As detailed in the API docs, your scheduled method must take a NSTimer * parameter:
- (void)timeCountDown:(NSTimer *)timer
Don't forget to change your selector in the scheduledTimerWithTimeInterval call to reflect this:
// There's a colon after selector name to denote
// the method takes one parameter
self.timeCounter = [NSTimer scheduledTimerWithTimeInterval:1
target:self selector:#selector(timeCountDown:) userInfo:nil repeats:YES];
If you don't want to pass as a arguement NSTimer* then use below after your timer
[self.timeCounter fire];

Timer Not Stopping when UIImage gets to a certain point

I am developing an app where the menu move away to reveal a second menu. I am moving the image with a NSTimer, and want it to stop when the image hits a certain coordinate on the screen. But what I am currently using is not working, it is moving the image, but it doesn't stop. What am I doing wrong? EDIT: This is Xcode 5
- (IBAction)showSubMenu:(id)sender {
moveTimer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:#selector(moveMenus) userInfo:nil repeats:YES];
[self stopMovement];
}
-(void)stopMovement {
if (mainMenu.center.y < -160) {
[moveTimer invalidate];
moveTimer = nil;
}
}
-(void)moveMenus {
mainMenu.center = (CGPointMake(mainMenu.center.x, mainMenu.center.y-1));
goButton.center = (CGPointMake(goButton.center.x, goButton.center.y-1));
Info.center = (CGPointMake(Info.center.x, Info.center.y-1));
helpButton.center = (CGPointMake(helpButton.center.x, helpButton.center.y-1));
subMenu.center = (CGPointMake(subMenu.center.x, subMenu.center.y-1));
description.center = (CGPointMake(description.center.x, description.center.y-1));
playEndless.center = (CGPointMake(playEndless.center.x, playEndless.center.y-1));
playQuick.center = (CGPointMake(playQuick.center.x, playQuick.center.y-1));
playSoundboard.center = (CGPointMake(playSoundboard.center.x, playSoundboard.center.y-1));
confirm.center = (CGPointMake(confirm.center.x, confirm.center.y-1));
}
Thanks for the help in advance!
Rafee
You need to call stopMovement every time your view move, so change your code like this :
- (IBAction)showSubMenu:(id)sender
{
moveTimer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:#selector(moveMenus) userInfo:nil repeats:YES];
}
- (void)stopMovement
{
if (mainMenu.center.y < -160)
{
[moveTimer invalidate];
moveTimer = nil;
}
}
- (void)moveMenus
{
mainMenu.center = (CGPointMake(mainMenu.center.x, mainMenu.center.y-1));
goButton.center = (CGPointMake(goButton.center.x, goButton.center.y-1));
Info.center = (CGPointMake(Info.center.x, Info.center.y-1));
helpButton.center = (CGPointMake(helpButton.center.x, helpButton.center.y-1));
subMenu.center = (CGPointMake(subMenu.center.x, subMenu.center.y-1));
description.center = (CGPointMake(description.center.x, description.center.y-1));
playEndless.center = (CGPointMake(playEndless.center.x, playEndless.center.y-1));
playQuick.center = (CGPointMake(playQuick.center.x, playQuick.center.y-1));
playSoundboard.center = (CGPointMake(playSoundboard.center.x, playSoundboard.center.y-1));
confirm.center = (CGPointMake(confirm.center.x, confirm.center.y-1));
// Call here
[self stopMovement];
}

NSTimer never starts

I'm just trying to close an NSPanel after a couple second delay, but I can't get my NSTimer to start. It will fire if I explicitly call the fire method on it, but it will never go by itself. Here's my code:
- (void)startRemoveProgressTimer:(NSNotification *)notification {
NSLog(#"timer should start");
timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:#selector(removeProgress:) userInfo:nil repeats:NO];
}
- (void)removeProgress:(NSTimer *)timer {
[progressPanel close];
}
I do have some threading in my code as such. I assume this is what's messing my timer up.
-(void)incomingTextUpdateThread:(NSThread*)parentThread {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
//mark the thread as running
readThreadRunning = TRUE;
const int BUFFER_SIZE = 100;
char byte_buffer[BUFFER_SIZE]; //buffer for holding incoming data
int numBytes = 0; //number of bytes read
NSString *text; //incoming text from the serial port
[NSThread setThreadPriority:1.0];
//this will loop until the serial port closes
while (TRUE) {
//read() blocks until some data is available or the port is closed
numBytes = read(serialFileDescriptor, byte_buffer, BUFFER_SIZE);
if(numBytes > 0) {
//creat a string from the incoming bytes
text = [[[NSString alloc] initWithBytes:byte_buffer length:numBytes encoding:[NSString defaultCStringEncoding]] autorelease];
if(!([text rangeOfString:SEND_NEXT_COORDINATE].location == NSNotFound)) {
//look for <next> to see if the next data should be sent
if(coordinateNum <[coordinatesArray count]) {
[self sendNextCoordinate]; //send coordinates
}
else {
[self writeString:FINISH_COORDINATES_TRANSMIT]; //send <end> to mark transmission as complete
NSNumber *total = [NSNumber numberWithUnsignedInteger:[coordinatesArray count]];
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:total forKey:#"progress"];
[[NSNotificationCenter defaultCenter] postNotificationName:#"uploadProgressChange" object:self userInfo:userInfo]; //update progress bar to completed
}
}
[self performSelectorOnMainThread:#selector(appendToIncomingText:) withObject:text waitUntilDone:YES]; //write incoming text to NSTextView
} else {
break; //Stop the thread if there is an error
}
}
// make sure the serial port is closed
if (serialFileDescriptor != -1) {
close(serialFileDescriptor);
serialFileDescriptor = -1;
}
// mark that the thread has quit
readThreadRunning = FALSE;
// give back the pool
[pool release];
}
Which is called from another method by: [self performSelectorInBackground:#selector(incomingTextUpdateThread:) withObject:[NSThread currentThread]];
Thank you rgeorge!!
Adding the timer to the run loop manually made it work!
timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:#selector(removeProgress:) userInfo:nil repeats:NO];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

Resources