Richard
Richard

Reputation: 125

Counter implementation using NsTimer in objective-c

I have surfed on a bunch of resources from the internet but still couldn't get any idea of what I'm trying to implement.

I hope this make sense!

Does anyone have any experience on this? I would be most appreciative if anyone can provide some codes and examples for me.

Upvotes: 0

Views: 7983

Answers (6)

Rajesh Loganathan
Rajesh Loganathan

Reputation: 11217

Try this simple method:

- (void)viewDidLoad 
{
   [super viewDidLoad];
   count = 0; // Declare int * count as global variable;
   [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
}

- (void)timerAction
{
    [self custom_method:count++]
}

Upvotes: 1

kagmanoj
kagmanoj

Reputation: 5368

Firstly I'd like to draw your attention to the Cocoa/CF documentation (which is always a great first port of call). The Apple docs have a section at the top of each reference article called "Companion Guides", which lists guides for the topic being documented (if any exist). For example, with NSTimer, the documentation lists two companion guides:

For your situation, the Timer Programming Topics article is likely to be the most useful, whilst threading topics are related but not the most directly related to the class being documented. If you take a look at the Timer Programming Topics article, it's divided into two parts:

  • Timers
  • Using Timers

For articles that take this format, there is often an overview of the class and what it's used for, and then some sample code on how to use it, in this case in the "Using Timers" section. There are sections on "Creating and Scheduling a Timer", "Stopping a Timer" and "Memory Management".There are a couple of ways of using a timer. From the article, creating a scheduled, non-repeating timer can be done something like this:

1) scheduled timer & using selector

NSTimer *t = [NSTimer scheduledTimerWithTimeInterval: 2.0
                  target: self
                  selector:@selector(onTick:)
                  userInfo: nil repeats:NO];
  • if you set repeats to NO, the timer will wait 2 seconds before running the selector and after that it will stop;
  • if repeat: YES, the timer will start immediatelly and will repeat calling the selector every 2 seconds;
  • to stop the timer you call the timer's -invalidate method: [t invalidate]; As a side note, instead of using a timer that doesn't repeat and calls the selector after a specified interval, you could use a simple statement like this:

    [self performSelector:@selector(onTick:) withObject:nil afterDelay:2.0];

this will have the same effect as the sample code above; but if you want to call the selector every nth time, you use the timer with repeats:YES;

2) self-scheduled timer

NSDate *d = [NSDate dateWithTimeIntervalSinceNow: 60.0];
NSTimer *t = [[NSTimer alloc] initWithFireDate: d
                          interval: 1
                          target: self
                          selector:@selector(onTick:)
                          userInfo:nil repeats:YES];

NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer:t forMode: NSDefaultRunLoopMode];
[t release];
  • this will create a timer that will start itself on a custom date specified by you (in this case, after a minute), and repeats itself every one second

3) unscheduled timer & using invocation

 NSMethodSignature *sgn = [self methodSignatureForSelector:@selector(onTick:)];
 NSInvocation *inv = [NSInvocation invocationWithMethodSignature: sgn];
 [inv setTarget: self];
 [inv setSelector:@selector(onTick:)];

 NSTimer *t = [NSTimer timerWithTimeInterval: 1.0
                  invocation:inv 
                  repeats:YES];

and after that, you start the timer manually whenever you need like this:

NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer: t forMode: NSDefaultRunLoopMode];

And as a note, onTick: method looks like this:

-(void)onTick:(NSTimer *)timer {
   //do smth
}

Upvotes: 2

rahul
rahul

Reputation: 178

Exactly As Dave Wood says You should use date and time for starting and ending viewing that screen and calculate the difference and then save it to any integer variable.Using NSTimer will make the performance effect in your app and make the compiler busy while incrementing the count.

Upvotes: 0

Dave Wood
Dave Wood

Reputation: 13333

You do not need to use NSTimers for this at all.

Store the date/time when the user starts viewing, and calculate the time difference when they stop viewing using simple time arithmetic.

Upvotes: 0

geminiCoder
geminiCoder

Reputation: 2906

Might I suggest a different route. If you take the time since reference date, when the user enters the page:

NSTimeINterval time = [NSDate timeIntervalSinceReferenceDate]

then do the same when they leave the page and compare them.

timeOnPage = time - time2;

This is much more efficient than firing a timer on another thread unnecessary.

Upvotes: 0

Shubhank
Shubhank

Reputation: 21805

ViewController A:

- (void)viewDidLoad {
   [super viewDidLoad];

    //create iVar of NSInteger *seconds
    seconds = 0;

    NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(increaseTimeCount) userInfo:nil repeats:YES];
    [timer fire];
}

- (void)increaseTimeCount {
    seconds++;
}

- (void)dealloc {
   NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    // you can add to array too , if you want and get average of all values later
   [defaults setInteger:seconds forKey: NSStringFromClass(self)];
}

now in Entrance View .. get the time as

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSInteger *secondsInView = [defaults integerForKey:NSStringFromClass(View1ClassName)];

Upvotes: 2

Related Questions