Search Results

Search found 152 results on 7 pages for 'nstimer'.

Page 1/7 | 1 2 3 4 5 6 7  | Next Page >

  • NSTimer as a self-targeting ivar.

    - by Matt Wilding
    I have come across an awkward situation where I would like to have a class with an NSTimer instance variable that repeatedly calls a method of the class as long as the class is alive. For illustration purposes, it might look like this: // .h @interface MyClock : NSObject { NSTimer* _myTimer; } - (void)timerTick; @end - // .m @implementation MyClock - (id)init { self = [super init]; if (self) { _myTimer = [[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timerTick) userInfo:nil repeats:NO] retain]; } return self; } - (void)dealloc { [_myTimer invalidate]; [_myTImer release]; [super dealloc]; } - (void)timerTick { // Do something fantastic. } @end That's what I want. I don't want to to have to expose an interface on my class to start and stop the internal timer, I just want it to run while the class exists. Seems simple enough. But the problem is that NSTimer retains its target. That means that as long as that timer is active, it is keeping the class from being dealloc'd by normal memory management methods because the timer has retained it. Manually adjusting the retain count is out of the question. This behavior of NSTimer seems like it would make it difficult to ever have a repeating timer as an ivar, because I can't think of a time when an ivar should retain its owning class. This leaves me with the unpleasant duty of coming up with some method of providing an interface on MyClock that allows users of the class to control when the timer is started and stopped. Besides adding unneeded complexity, this is annoying because having one owner of an instance of the class invalidate the timer could step on the toes of another owner who is counting on it to keep running. I could implement my own pseudo-retain-count-system for keeping the timer running but, ...seriously? This is way to much work for such a simple concept. Any solution I can think of feels hacky. I ended up writing a wrapper for NSTimer that behaves exactly like a normal NSTimer, but doesn't retain its target. I don't like it, and I would appreciate any insight.

    Read the article

  • NSTimer timestamp timeinterval question

    - by okami
    I have the following code: [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timerCount:) userInfo:nil repeats:YES]; -(void)timerCount:(NSTimer *)timer { NSTimeInterval dt = [timer timeInterval]; // do something } The NSTimeInterval I got will be 0.5, the time interval I've put on scheduledTimerWithInterval, this means the timerCount will be called each 0.5 seconds. But I now that there are some stuff as timeStamps, and I want to know if the NSTimer will call the timerCount method in PRECISELY 0.5 seconds each time.

    Read the article

  • NSTimer to fire while device is locked

    - by edie
    Hi, I'm currently creating an alarm. I use NSTimer to schedule my alarms. My problem is when the device was put into locked mode my NSTimer doesn't fire. I think that the NSTimer will not fire because my app goes to suspended state when it is lock. Can you help me find a solution to my problem? I've found some topics about UIBackgroundModes, but I don't know how it will help me. Thanks.. The problem in UILocalNotification is when the device was in silent, the sound will not be hear. My implementation was I'm using NSTimer to fire an alarm when the app is in foreground or device is locked but app currently running. When the applicationDidEnterBackground: is called I schedule the UILocalNotification as the alarm.

    Read the article

  • NSTimer as a timeout mechanism

    - by alexantd
    I'm pretty sure this is really simple, and I'm just missing something obvious. I have an app that needs to download data from a web service for display in a UITableView, and I want to display a UIAlertView if the operation takes more than X seconds to complete. So this is what I've got (simplified for brevity): MyViewController.h @interface MyViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> { NSTimer *timer; } @property (nonatomic, retain) NSTimer *timer; MyViewController.m @implementation MyViewController @synthesize timer; - (void)viewDidLoad { timer = [NSTimer scheduledTimerWithTimeInterval:20 target:self selector:@selector(initializationTimedOut:) userInfo:nil repeats:NO]; [self doSomethingThatTakesALongTime]; [timer invalidate]; } - (void)doSomethingThatTakesALongTime { sleep(30); // for testing only // web service calls etc. go here } - (void)initializationTimedOut:(NSTimer *)theTimer { // show the alert view } My problem is that I'm expecting the [self doSomethingThatTakesALongTime] call to block while the timer keeps counting, and I'm thinking that if it finishes before the timer is done counting down, it will return control of the thread to viewDidLoad where [timer invalidate] will proceed to cancel the timer. Obviously my understanding of how timers/threads work is flawed here because the way the code is written, the timer never goes off. However, if I remove the [timer invalidate], it does.

    Read the article

  • Schedule timer with NSTimer makes the task run faster than expected

    - by Hoang Pham
    I schedule a timer with NSTimer's function in viewWillAppear as follows: minutesTimer = nil; minutesTimer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(updateScrollViewItems) userInfo:NULL repeats:YES]; With this function call, I expect it to call the selector updateScrollViewItems every minute, but it does not, it update items faster than expected (around some seconds). What is the cause of this unexpected behavior?

    Read the article

  • Releasing an NSTimer iPhone?

    - by Conor Taylor
    I have an NSTimer declared in my .h and in the viewDidLoad of the /m I have the code: timer = [NSTimer scheduledTimerWithTimeInterval:kComplexTimer target:self selector:@selector (main) userInfo:nil repeats:YES]; I also have [timer release]; in my dealloc. However when I exit the view and return to it, the timer has not in fact released, it has doubles in speed! How do I solve this & what am I doing wrong??? Thanks

    Read the article

  • NSTimer calculate hours

    - by Nic Hubbard
    I am using an NSTimer which I have working to show minutes and seconds. But I am confused about the math needed to calculate hours. I am using: - (void)updateCounter:(NSTimer *)theTimer { static int count = 0; count += 1; int seconds = count % 60; int minutes = (count - seconds) / 60; // Not sure how to calculate hours int hours = (count - minutes) / 60; self.timer.text = [NSString stringWithFormat:@"%.2d:%.2d:%.2d", hours, minutes, seconds]; } What calculation should I use for hours?

    Read the article

  • Passing Data thru NSTimer UserInfo

    - by zorro2b
    I a trying to pass data thru userInfo for an NSTimer call. What is the best way to do this? I am trying to use an NSDictionary, this is simple enough when I have objective c objects, but what about other data? I want to do something like this, which doesn't work as is: - (void) play:(SystemSoundID)sound target:(id)target callbackSelector:(SEL)selector { NSLog(@"pause ipod"); [iPodController pause]; theSound = sound; NSMutableDictionary *cb = [[NSMutableDictionary alloc] init]; [cb setObject:(id)&sound forKey:@"sound"]; [cb setObject:target forKey:@"target"]; [cb setObject:(id)&selector forKey:@"selector"]; [NSTimer scheduledTimerWithTimeInterval:0 target:self selector: @selector(notifyPause1:) userInfo:(id)cb repeats:NO]; }

    Read the article

  • Displaying timecode using NSTimer and NSDateFormatter

    - by Chris B
    Hi. I am very close to completing my first iphone app and it has been a joy. I am trying to add running timecode using the current time via an NSTimer displaying the current time (NSDate) on a UILabel. NSDate is working fine for me, showing hour, minute, second, milliseconds. But instead of milliseconds, I need to show 24 frames per second. The problem is that I need the frames per second to be synced 100% with the hour, minute and second, so I can't add the frames in a separate timer. I tried that and had it working but the frame timer was not running in sync with the date timer. Can anyone help me out with this? Is there a way to customize NSDateFormatter so that I can have a date timer formatted with 24 frames per second? Right now I'm limited to formatting just hours, minutes, seconds, and milliseconds. Here's the code I'm using right now -(void)runTimer { // This starts the timer which fires the displayCount method every 0.01 seconds runTimer = [NSTimer scheduledTimerWithTimeInterval: .01 target: self selector: @selector(displayCount) userInfo: nil repeats: YES]; } //This formats the timer using the current date and sets text on UILabels - (void)displayCount; { NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease]; NSDate *date = [NSDate date]; // This will produce a time that looks like "12:15:07:75" using 4 separate labels // I could also have this on just one label but for now they are separated // This sets the Hour Label and formats it in hours [formatter setDateFormat:@"HH"]; [timecodeHourLabel setText:[formatter stringFromDate:date]]; // This sets the Minute Label and formats it in minutes [formatter setDateFormat:@"mm"]; [timecodeMinuteLabel setText:[formatter stringFromDate:date]]; // This sets the Second Label and formats it in seconds [formatter setDateFormat:@"ss"]; [timecodeSecondLabel setText:[formatter stringFromDate:date]]; //This sets the Frame Label and formats it in milliseconds //I need this to be 24 frames per second [formatter setDateFormat:@"SS"]; [timecodeFrameLabel setText:[formatter stringFromDate:date]]; }

    Read the article

  • NSTimer to smooth out playback position

    - by Michael
    I have an audio player and I want to show the current time of the the playback. I'm using a custom play class. The app downloads the mp3 to a file then plays from the file when 5% has been downloaded. I have a progress view update as the file plays and update a label on each call to the progress view. However, this is jerky... sometimes even going backward a digit or two. I was considering using an NSTimer to smooth things out. I would be fired every second to a method and pass the percentage played figure to the method then update the label. First, does this seem reasonable? Second, how do I pass the percentage (a float) over to the target of the timer. Right now I am putting the percent played into a dictionary but this seems less than optimal. This is what is called update the progress bar: -(void)updateAudioProgress:(Percentage)percent { audio = percent; if (!seekChanging) slider.value = percent; NSMutableDictionary *myDictionary = [[NSMutableDictionary alloc] init]; [myDictionary setValue:[NSNumber numberWithFloat:percent] forKey:@"myPercent"]; [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(myTimerMethod:) userInfo:myDictionary repeats:YES]; [myDictionary release]; } This is called first after 5 seconds but then updates each time the method is called. As always, comments and pointers appreciated.

    Read the article

  • iPhone NSTimer OpenGL problem

    - by Toby Wilson
    I've got a problem that only seems to occur on the device, not in the simulator. My app's animation is started and stopped using these methods: NSTimer* animationTimer; -(void)startAnimation { if(animationTimer = nil) animationTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f/60.0f target:self selector:@selector(drawView) userInfo:nil repeats:YES]; } -(void)stopAnimation { [animationTimer invalidate]; animationTimer = nil; } In the simulator this works fine and drawView starts being called at 60fps. On the device (testing on iPod Touch), the scheduleTimerWithTimeInterval method doesn't seem to work. Furthermore, [animationTimer invalidate] causes EXC_BAD_ACCESS. I've spotted an obvious but minor flaw; adding if(animationTimer != nil) to the stopAnimation method will prevent the crash, but doesn't solve the problem of the animation timer not being properly initialised. Edit: The above doesn't prevent a crash. animationTimer != nil yet calling invalidate causes EXC_BAD_ACCESS. Should also add, this problem doesn't occur all the time on the device. Maybe 40% of the time.

    Read the article

  • iPhone: Using dispatch_after to mimick NSTimer

    - by Joseph Tura
    Don't know a whole lot about blocks. How would you go about mimicking a repeating NSTimer with dispatch_after? My problem is that I want to "pause" a timer when the app moves to the background, but subclassing NSTimer does not seem to work. I tried something which seems to work. I cannot judge its performance implications or whether it could be greatly optimized. Any input is welcome. #import "TimerWithPause.h" @implementation TimerWithPause @synthesize timeInterval; @synthesize userInfo; @synthesize invalid; @synthesize invocation; + (TimerWithPause *)scheduledTimerWithTimeInterval:(NSTimeInterval)aTimeInterval target:(id)aTarget selector:(SEL)aSelector userInfo:(id)aUserInfo repeats:(BOOL)aTimerRepeats { TimerWithPause *timer = [[[TimerWithPause alloc] init] autorelease]; timer.timeInterval = aTimeInterval; NSMethodSignature *signature = [[aTarget class] instanceMethodSignatureForSelector:aSelector]; NSInvocation *aInvocation = [NSInvocation invocationWithMethodSignature:signature]; [aInvocation setSelector:aSelector]; [aInvocation setTarget:aTarget]; [aInvocation setArgument:&timer atIndex:2]; timer.invocation = aInvocation; timer.userInfo = aUserInfo; if (!aTimerRepeats) { timer.invalid = YES; } [timer fireAfterDelay]; return timer; } - (void)fireAfterDelay { dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, self.timeInterval * NSEC_PER_SEC); dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_after(delay, queue, ^{ [invocation performSelectorOnMainThread:@selector(invoke) withObject:nil waitUntilDone:NO]; if (!invalid) { [self fireAfterDelay]; } }); } - (void)invalidate { invalid = YES; [invocation release]; invocation = nil; [userInfo release]; userInfo = nil; } - (void)dealloc { [self invalidate]; [super dealloc]; } @end

    Read the article

  • NSTimer Reset Not Working

    - by user355900
    hi, i have a nstimer and it works perfectly counting down from 2:00 but when i hit the reset button it does not work it just stops the timer and when i press start again it will carry on with the timer as if it had never been stopped. Here is my code `@implementation TimerAppDelegate @synthesize window; (void)applicationDidFinishLaunching:(UIApplication *)application { timerLabel.text = @"2:00"; seconds = 120; // Override point for customization after application launch [window makeKeyAndVisible]; } (void)viewDidLoad { [timer invalidate]; } (void)countDownOneSecond { seconds--; int currentTime = [timerLabel.text intValue]; int newTime = currentTime - 1; int displaySeconds = !(seconds % 60) ? 0 : seconds < 60 ? seconds : seconds - 60; int displayMinutes = floor(seconds / 60); NSString *time = [NSString stringWithFormat:@"%d:%@%d", displayMinutes, [[NSString stringWithFormat:@"%d", displaySeconds] length] == 1 ? @"0" : @"", displaySeconds ]; timerLabel.text = time; if(seconds == 0) { [timer invalidate]; } } (void)startOrStopTimer { if(timerIsRunning){ [timer invalidate]; [startOrStopButton setTitle:@"Start" forState:UIControlStateNormal]; } else { timer = [[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDownOneSecond) userInfo:nil repeats:YES] retain]; [startOrStopButton setTitle:@"Stop" forState:UIControlStateNormal]; } timerIsRunning = !timerIsRunning; } (void)resetTimer { [timer invalidate]; [startOrStopButton setTitle:@"Start" forState:UIControlStateNormal]; [timer invalidate]; timerLabel.text = @"2:00"; } (void)dealloc { [window release]; [super dealloc]; } @end` thanks

    Read the article

  • probelem with NSTimer

    - by zp26
    Hi I have a problem with a NSTimer I recived a "SIGABRT" error and "[NSCFTimer intValue]: unrecognized selector sent to instance " These is my code: -(void)detectionMove:(NSNumber*)arrayIndex{ static BOOL notFind = FALSE; static int countVariable = 0; static int countRilevamenti = 0; notFind = FALSE; for(int i = countVariable+1; i<[[[[sharedController arrayMovement]objectAtIndex:[arrayIndex intValue]] arrayPositionMove]count]; i++){ if(!notFind){ if((actualAccelerometerX+sensibilityMovement) >= [[[[[sharedController arrayMovement]objectAtIndex:[arrayIndex intValue]] arrayPositionMove]objectAtIndex:i]valueX] && (actualAccelerometerX-sensibilityMovement) <= [[[[[sharedController arrayMovement]objectAtIndex:[arrayIndex intValue]] arrayPositionMove]objectAtIndex:i]valueX] && (actualAccelerometerY+sensibilityMovement) >= [[[[[sharedController arrayMovement]objectAtIndex:[arrayIndex intValue]] arrayPositionMove]objectAtIndex:i]valueY] && (actualAccelerometerY-sensibilityMovement) <= [[[[[sharedController arrayMovement]objectAtIndex:[arrayIndex intValue]] arrayPositionMove]objectAtIndex:i]valueY] && (actualAccelerometerZ+sensibilityMovement) >= [[[[[sharedController arrayMovement]objectAtIndex:[arrayIndex intValue]] arrayPositionMove]objectAtIndex:i]valueZ] && (actualAccelerometerZ-sensibilityMovement) <= [[[[[sharedController arrayMovement]objectAtIndex:[arrayIndex intValue]] arrayPositionMove]objectAtIndex:i]valueZ]) { countVariable = i; notFind = TRUE; countRilevamenti++; } } } if(!notFind) return; else if(countVariable+1 == [[[[sharedController arrayMovement]objectAtIndex:[arrayIndex intValue]] arrayPositionMove]count]){ if(countRilevamenti + tollerance >= [[[[sharedController arrayMovement]objectAtIndex:[arrayIndex intValue]] arrayPositionMove]count]) movementDetected = [arrayIndex intValue]; else NSLog(@"troppo veloce"); countVariable = 0; notFind = FALSE; countRilevamenti = 0; return; } [NSTimer scheduledTimerWithTimeInterval:timeToCatch target:self selector:@selector(detectionMove:) userInfo:(NSNumber*)arrayIndex repeats:NO]; }

    Read the article

  • How can I break from a method prematurely that's being called by NSTimer

    - by jammur
    Basically I'm writing a metronome app, but I'm using a sound file that, depending on the BPM, might not be finished playing when the "play" method is called again. For example, if the sound file is 0.5 seconds long, but the BPM is 200, the "play" method needs to be called every 0.3 seconds. I'm not overly familiar with NSTimer, but it appears that if it is supposed to fire before the previous invocation has completed, it doesn't, and just waits for the next time around. I could be completely wrong about that though. What I need to do is have the previous invocation end prematurely, and have the "play" method called again when the time is supposed to fire. Any help would be appreciated!

    Read the article

  • Running and managing NSTimer in different NSThread/NSRunLoop

    - by mips
    I'm writing a Cocoa application, with a GUI designed in Interface Builder. I need to schedule background activity (at regular intervals) without blocking the UI, so I run it in a separate thread, like this: - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { [self performSelectorInBackground:@selector(schedule) withObject:nil]; } - (void) schedule { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; NSRunLoop* runLoop = [NSRunLoop currentRunLoop]; timer = [[NSTimer scheduledTimerWithTimeInterval:FEED_UPDATE_INTERVAL target:activityObj selector:@selector(run:) userInfo:nil repeats:YES] retain]; [runLoop run]; [pool release]; } I retain the timer, so I can easily invalidate and reschedule. Problem: I must also fire the run: method in response to GUI events, so it is synchronous (i.e. a "perform activity" button). Like this: [timer fire]; I could do this with performSelectorInBackground too, and of course it doesn't block the UI. But this synchronous firings run in another runloop! So I have no guarantee that they won't overlap. How can I queue all of my firings on the same runloop?

    Read the article

  • Schedule multiple events with NSTimer?

    - by AWright4911
    I have a schedule cache stored in a pList. For the example below, I have a schedule time of April 13, 2010 2:00PM and Aril 13, 2010 2:05PM. How can I add both of these to a queue to fire on their own? item 0 -Hour --14 -Minute --00 -Month --04 -Day --13 -Year --2010 item 1 -Hour --14 -Minute --05 -Month --04 -Day --13 -Year --2010 this is how I am attempting to schedule multiple events to fire at specific date / time. -(void) buildScheduleCache { MPNotifyViewController *notifier = [MPNotifyViewController alloc] ; [notifier setStatusText:@"Rebuilding schedule cache, this will only take a moment."]; [notifier show]; NSCalendarDate *now = [NSCalendarDate calendarDate]; NSFileManager *manager = [[NSFileManager defaultManager] autorelease]; path = @"/var/mobile/Library/MobileProfiles/Custom Profiles"; theProfiles = [manager directoryContentsAtPath:path]; myPrimaryinfo = [[NSMutableArray arrayWithCapacity:6] retain]; keys = [NSArray arrayWithObjects:@"Profile",@"MPSYear",@"MPSMonth",@"MPSDay",@"MPSHour",@"MPSMinute",nil]; for (NSString *profile in theProfiles) { plistDict = [[[NSMutableDictionary alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",path,profile]] autorelease]; [myPrimaryinfo addObject:[NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: [NSString stringWithFormat:@"%@",profile], [NSString stringWithFormat:@"%@",[plistDict objectForKey:@"MPSYear"]], [NSString stringWithFormat:@"%@",[plistDict objectForKey:@"MPSMonth"]], [NSString stringWithFormat:@"%@",[plistDict objectForKey:@"MPSDay"]], [NSString stringWithFormat:@"%@",[plistDict objectForKey:@"MPSHour"]], [NSString stringWithFormat:@"%@",[plistDict objectForKey:@"MPSMinute"]], nil]forKeys:keys]]; profileSched = [NSCalendarDate dateWithYear:[plistDict objectForKey:@"MPSYear"] month:[plistDict objectForKey:@"MPSMonth"] day:[plistDict objectForKey:@"MPSDay"] hour:[plistDict objectForKey:@"MPSHour"] minute:[plistDict objectForKey:@"MPSMinute"] second:01 timeZone:[now timeZone]]; [self rescheduleTimer]; } NSString *testPath = @"/var/mobile/Library/MobileProfiles/Schedules.plist"; [myPrimaryinfo writeToFile:testPath atomically:YES]; } -(void) rescheduleTimer { timer = [[NSTimer alloc] initWithFireDate:profileSched interval:0.0f target:self selector:@selector(theFireEvent) userInfo:nil repeats:YES]; NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; [runLoop addTimer:timer forMode:NSDefaultRunLoopMode]; }

    Read the article

  • iPhone OpenGL and NSTimer issues

    - by Kyle
    I have an NSTimer that runs at 60hz. With an OpenGL scene loaded and rendering, my game can get 60fps, solid, all day long.. Then if I go and recompile the app, or reload it, it will get 40fps. Same resources loaded. I've been running into this problem for years, and I just want to know why. It's crazy, and I want to know if I should just abandon this stupid Timer. Conditions are not different on my 3GS between loads. It will just get 40fps sometimes. Obviously the clockrate is not different between loads, so the performance figures should be constant given a constant scene. Here is a log of my framerates: A good load: :-) FrameRate: 61 FrameRate: 61 FrameRate: 61 FrameRate: 60 FrameRate: 60 FrameRate: 61 FrameRate: 60 FrameRate: 60 FrameRate: 61 FrameRate: 60 FrameRate: 61 Now, I'll go ahead and do nothing, recompile, and run: FrameRate: 43 FrameRate: 50 FrameRate: 45 FrameRate: 48 FrameRate: 40 FrameRate: 45 FrameRate: 42 FrameRate: 41 FrameRate: 42 FrameRate: 44 FrameRate: 41 FrameRate: 46 ^- Massive difference visually. What the flying heck could cause this? SAME area of the scene, SAME camera setup. No variables are different.

    Read the article

  • NSTimer won't stop it only resets when invalidated & released

    - by J Fries
    When I press my stop button to stop the timer it just resets to the original time and begins counting down again. I have looked everywhere and all I have found is "invalidate" and it isn't working. I want the time to stop when I hit stop and the label to display the original time. I also turned off automatic counting so I could try releasing and it is giving me an error: 0x10e20a5: movl 16(%edx), %edx EXC_BAD_ACCESS (code=2, address=0x10) `NSTimer *rockettTimer; int rocketCount; @interface FirstViewController () @property (strong, nonatomic) IBOutlet UILabel *rocketTimer; - (IBAction)stopButton:(id)sender; - (IBAction)startButton:(id)sender; @end @implementation FirstViewController @synthesize rocketTimer; -(void) rocketTimerRun{ rocketCount = rocketCount - 1; int minuts = rocketCount / 60; int seconds = rocketCount - (minuts * 60); NSString *timerOutput = [NSString stringWithFormat:@"%d:%.2d", minuts, seconds]; rocketTimer.text = timerOutput; } - (IBAction)startButton:(id)sender { rocketCount = 180; rockettTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(rocketTimerRun) userInfo:nil repeats:YES]; - (IBAction)stopButton:(id)sender { [rockettTimer invalidate]; //[rockettTimer release]; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } - (void)viewDidUnload { [self setRocketTimer:nil]; [super viewDidUnload]; // Release any retained subviews of the main view. } - (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation { if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) { return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); } else { return YES; } } @end`

    Read the article

  • Countdown timer using NSTimer in "0:00" format

    - by Joey Pennacchio
    I have been researching for days on how to do this and nobody has an answer. I am creating an app with 5 timers on the same view. I need to create a timer that counts down from "15:00" (minutes and seconds), and, another that counts down from "2:58" (minutes and seconds). The 15 minute timer should not repeat, but it should stop all other timers when it reaches "00:00." The "2:58" timer should repeat until the "15:00" or "Game Clock" reaches 0. Right now, I have scrapped almost all of my code and I'm working on the "2:58" repeating timer, or "rocketTimer." Does anyone know how to do this? Here is my code: #import <UIKit/UIKit.h> @interface FirstViewController : UIViewController { //Rocket Timer int totalSeconds; bool timerActive; NSTimer *rocketTimer; IBOutlet UILabel *rocketCount; int newTotalSeconds; int totalRocketSeconds; int minutes; int seconds; } - (IBAction)Start; @end and my .m #import "FirstViewController.h" @implementation FirstViewController - (NSString *)timeFormatted:(int)newTotalSeconds { int seconds = totalSeconds % 60; int minutes = (totalSeconds / 60) % 60; return [NSString stringWithFormat:@"%i:%02d"], minutes, seconds; } -(IBAction)Start { newTotalSeconds = 178; //for 2:58 newTotalSeconds = newTotalSeconds-1; rocketCount.text = [self timeFormatted:newTotalSeconds]; if(timerActive == NO){ timerActive = YES; newTotalSeconds = 178; [rocketTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerLoop) userInfo:nil repeats:YES]; } else{ timerActive = NO; [rocketTimer invalidate]; rocketTimer = nil; } } -(void)timerLoop:(id)sender { totalSeconds = totalSeconds-1; rocketCount.text = [self timeFormatted:totalSeconds]; } - (void)dealloc { [super dealloc]; [rocketTimer release]; } - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view from its nib. timerActive = NO; } - (void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return (interfaceOrientation == UIInterfaceOrientationPortrait); } @end

    Read the article

  • iPhone: NSTimer Countdown (Display Minutes:Seconds)

    - by user298261
    Hello! I have my timer code set up, and it's all kosher, but I want my label to display "Minutes : seconds" instead of just seconds. -(void)countDown{ time -= 1; theTimer.text = [NSString stringWithFormat:@"%i", time]; if(time == 0) { [countDownTimer invalidate]; } } I've already set "time" to 600, or 10 minutes. However, I want the display to show 10:59, 10:58, etc. until it reaches zero. How do I do this? Thanks!

    Read the article

  • Application crash when using an NSTimer and pushViewController

    - by Cesar
    I'm using an NSTimer to implement a 3 seconds splash screen. If a don't use a timer the view it's correctly pushed but if I use the timer for adding a little delay the application crash with a EXC_BAD_ACCESS. I'm pretty sure the answer contains "memory management" but I can't get the point... @interface RootViewController : UIViewController { NSTimer *timer; } -(void)changeView:(NSTimer*)theTimer; @property(nonatomic,retain) NSTimer *timer; ... @implementation RootViewController @synthesize timer; - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; [[self navigationController] setNavigationBarHidden:YES]; timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(changeView:) userInfo:nil repeats:NO]; } -(void)changeView:(NSTimer*)theTimer { NSLog(@"timer fired"); //Crash here, but only if called using a timer [[self navigationController] pushViewController:list animated:YES]; }

    Read the article

  • NSTimer freezes the app until it gets fired again?

    - by itai alter
    Hello all, I have a simple app with a button, UIImageView and a NSTimer. The timer is fired up every 5 seconds repeatedly to update the ImageView with a new image, while the button simply stops the timer and switches to another View. The problem is that when I press the button, nothing happens for a few seconds (until the timer fires up again). Is there a way to cause the button to stop the timer and do its job at any given time instead of between intervals of the timer? Thanks!

    Read the article

1 2 3 4 5 6 7  | Next Page >