Display each object in NSArray for 2 seconds - iphone

I have the following problem: I have an NSArray that contains 5 objects. I want to display each item for 2 seconds using NSTimer, and release the timer after displaying the last item in the array.
Country = [NSArray arrayWithObjects:#"Aus",#"India",#"Pak",#"China",#"Japan", nil];
cntcount = [Country count];
NSLog(#"concount=%i", cntcount);
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:#selector(startTime) userInfo:nil repeats:YES];
But I'm not getting another step. What should I do in the starttime() function? Please help!
//
// AppViewController.m
// NSTimerExample
//
#import "AppViewController.h"
#interface AppViewController ()
#end
#implementation AppViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
Country = [NSArray arrayWithObjects:
#"Aus", #"India", #"Pak", #"China", #"Japan", nil];
tempValue = 0;
NSTimer *popupTimer = [NSTimer scheduledTimerWithTimeInterval:2.0
target:self
selector:#selector(startTime:)
userInfo:nil
repeats:YES];
NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer:popupTimer forMode:NSDefaultRunLoopMode];
}
- (void)startTime:(NSTimer *)theTimer {
int cntcount = [Country count];
if(tempValue < cntcount) {
NSString *objectName = [Country objectAtIndex:tempValue];
NSLog(#"objectName=%#", objectName);
tempValue++;
} else {
[theTimer invalidate];
theTimer = nil;
// or you can reset tempValue to 0.
}
}
After displaying the last item I want to release timer as it is no longer needed, but I'm getting and EXC_BAD_ACCESS exception.

Do like this,
In .h
int tempValue;
In .m
tempValue=0;
NSTimer *popupTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:#selector(startTime:) userInfo:nil repeats:YES];;
NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer:popupTimer forMode: NSDefaultRunLoopMode];
In timer action method:
-(void)startTime:(NSTimer*)theTimer {
if(tempValue< Country.count) {
// Display array object eg: label.text=[Country objectAtIndex:tempValue];
tempValue++;
} else {
[theTimer invalidate];
theTimer=nil;
// or you can reset the tempValue into 0.
}
}

#import "AppViewController.h"
#interface AppViewController ()
#end
#implementation AppViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
Country=[[NSArray alloc]initWithObjects:#"Aus",#"India",#"Pak",#"China",#"Japan", nil];
tempValue=0;
NSTimer *popupTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:#selector(startTime:) userInfo:nil repeats:YES];;
NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer:popupTimer forMode: NSDefaultRunLoopMode];
}
- (void)startTime:(NSTimer*)theTimer {
if(tempValue< Country.count) {
NSString *objectname=[Country objectAtIndex:tempValue];
NSLog(#"objectname is %#",objectname);
tempValue++;
} else {
[theTimer invalidate];
theTimer=nil;
// or you can reset the tempValue into 0.
}
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#end
thanks to Tony and this code is working properly

Related

How to run another thread and using that thread run timer to repeat process?

Hi i want to start a timer with another thread and want to repeat process in that thread. i had tried but it doesn't work.
my code snippet is given below
[NSThread detachNewThreadSelector:#selector(setupTimerThread) toTarget:self withObject:nil];
-(void)setupTimerThread
{
NSLog(#"inside setup timer thread");
// self.startTiemr = [[NSTimer alloc]init];
startTiemr = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:#selector(triggerTimer) userInfo:nil repeats:YES];
runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:startTiemr forMode:NSRunLoopCommonModes];
[runLoop run];
}
can anyone suggest me a proper way to do that?
Thanks in advance.
#import "TimePassViewController.h"
#interface TimePassViewController ()
#end
#implementation TimePassViewController
{
NSTimer *timer;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// [self performSelectorOnMainThread:#selector(yourmethod) withObject:nil waitUntilDone:NO];
NSThread* myThread = [[NSThread alloc] initWithTarget:self
selector:#selector(yourmethod)
object:nil];
[myThread start]; // Actually create the thread
}
-(void)yourmethod
{
#autoreleasepool
{
NSRunLoop *TimerRunLoop = [NSRunLoop currentRunLoop];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(timerMethod) userInfo:nil repeats:YES];
[TimerRunLoop run];
}
//timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(timerMethod) userInfo:nil repeats:YES];
}
-(void)timerMethod
{
NSLog(#"aaaaaaaaaaaa");
//[timer invalidate];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
try this code:
NStimer *uptimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(bachground_todaylist) userInfo:nil repeats:YES];
-(void)bachground_todaylist
{
[self performSelectorInBackground:#selector(yourmethod) withObject:nil];
}
you wants to stop proces
[uptimer invalidate];

Resetting Timer issues IOS

I'm working on a buzzer app for IOS. When you click the buzzer, it buzzes, 30 seconds pops up, and counts down until after 1 and then buzzes and disappears. If, during the course of the 30-second countdown, someone wants to reset the buzzer (so that the timer goes off and disappears), they will just click the buzzer again.
I have three questions:
1. How do you start the app with the UILabel invisible and then shows up upon the first click?
2. How do you reset the buzzer by clicking it during the 30 second countdown?
3. Will reseting the buzzer fix the problem of the timer going down extremely quick when clicked multiple times?
viewcontrol.h
#import <UIKit/UIKit.h>
#import <AudioToolbox/AudioToolbox.h>
#interface ViewController : UIViewController {
IBOutlet UILabel *seconds;
NSTimer *timer;
int MainInt;
SystemSoundID buzzer;
}
- (IBAction)start:(id)sender;
- (void)countdown;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
-(IBAction)start:(id)sender {
seconds.hidden = NO;
MainInt = 30;
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(countdown) userInfo:nil repeats:YES];
AudioServicesPlaySystemSound(buzzer);
}
-(void)countdown {
MainInt -= 1;
seconds.text = [NSString stringWithFormat:#"%i", MainInt];
if (MainInt < 1) {
[timer invalidate];
timer = nil;
seconds.hidden = YES;
AudioServicesPlaySystemSound(buzzer);
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSURL *buttonURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"Buzz" ofType:#"wav"]];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)buttonURL, &buzzer);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
1) hiding the label on startup
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//hide the label initially
[seconds setHidden:YES];
/// other code
then call [seconds setHidden:NO]; in start method
2) reset buzzer
-(IBAction)start:(id)sender {
seconds.hidden = NO;
MainInt = 30;
if(timer != nil)
{
//timer exist..stop previous timer first.
[timer invalidate];
}
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(countdown) userInfo:nil repeats:YES];
AudioServicesPlaySystemSound(buzzer);
}
1) For the label becoming visible on a delay, initialize the label (in code or in IB) with seconds.alpha = 0.0. Then to make it visible...
NSTimeInterval delayUntilLabelIsVisible = 3.0; // 3 seconds
[UIView animateWithDuration:0.3
delay:delayUntilLabelIsVisible
options:UIViewAnimationCurveEaseIn
animations:^{seconds.alpha = 1.0;}
completion:^(BOOL finished) {}];
2,3) Your second and third questions can be solved with a line of code in the start method...
-(IBAction)start:(id)sender {
seconds.hidden = NO;
MainInt = 30;
// cancel the old timer before creating a new one
// (otherwise many timers will run at once, calling the buzzer method too often)
[timer invalidate];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(countdown) userInfo:nil repeats:YES];
AudioServicesPlaySystemSound(buzzer);
}

Images not getting changed with NSTimer

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];

Unable to get NSTimer to work

Using NSTimer for my application in which I have to show countdown timer with initial timing equal to 100sec. It shows 99,then 98..96..94..92...86 and so on. But I want each sec to show up. Here is my code....
-(void)updateTimerLabel{
if (timeRemaining>0 ) {
timeRemaining=timeRemaining-1.0;
timerLabel.text=[NSString stringWithFormat:#"%.0f", timeRemaining];
countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(updateTimerLabel) userInfo:nil repeats:YES];
}
}
Try following code
int i =100;
-(void)viewDidLoad
{
[super viewDidLoad];
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(theActionMethod) userInfo:nil repeats:YES];
}
-(void)theActionMethod
{
if(i > 0)
{
NSString *str = [NSString stringWithFormat:#"%d",i];
lbl.text = str;
}
i--;
}
You are actually re-creating the timer every time your method gets called.
You should try leaving that outside and retaining it until you're finished with it.
#interface SomeClass
NSTimer * aTimer;
#end
#implementation
- (void)createTimer {
aTimer = [[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(updateTimerLabel) userInfo:nil repeats:YES] retain];
}
- (void)updateTimerLabel {
// do timer updates here
// call [aTimer release]
// and [aTimer invalidate]
// aTimer = nil;
// when you're done
}
#end
you have call updateTimerLabel outside the method.
ex:
-(void)viewDidLoad{timeRemaining=100.0;[self updateTimerLabel];countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(updateTimerLabel) userInfo:nil repeats:YES];}
-(void)updateTimerLabel
{if (timeRemaining>0 )
{timeRemaining=timeRemaining-1.0;NSLog(#"%#",[NSString stringWithFormat:#"%.0f",timeRemaining]);}}

IOS set same but different objects to one memory address

#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