Doug Smith
Doug Smith

Reputation: 29326

If I want to execute a method every x seconds y times, should I use NSTimer?

I want to make something different appear every 2 seconds say, 10 times. How would I go about achieving this in Objective-C?

I was thinking about using NSTimer and invalidating it after so many seconds, like in the above example 2 * 10 seconds after I start the timer. Or is there a way to measure the ticks?

Or I was considering a for loop and using the performSelector:withDelay: method.

Which would be preferable?

Upvotes: 3

Views: 3837

Answers (2)

Shamsudheen TK
Shamsudheen TK

Reputation: 31311

Use NSTimer and set the time interval as 2 seconds and repeats to YES.

Count the number of times that it triggered. Invalidate when it reaches 10.Thats it

Code:

[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(trigger:) userInfo:yourObject repeats:YES];

- (void)trigger:(NSTimer *)sender{

    id yourObject = sender.userInfo;

    static int count = 1;

    @try {

        NSLog(@"triggred %d time",count);

        if (count == 10){

            [sender invalidate];
            NSLog(@"invalidated");
        }

    }
    @catch (NSException *exception)
    {
        NSLog(@"%s\n exception: Name- %@ Reason->%@", __PRETTY_FUNCTION__,[exception name],[exception reason]);
    }
    @finally {

        count ++;
    }
}

Upvotes: 7

meth
meth

Reputation: 1885

i used the second option of you, no timer needed

for (int a=0; a<10; a++) {
    [self performSelector:@selector(print) withObject:nil afterDelay:2.0*a];
}


-(void)print
{
    NSLog(@"sth");
}

you may make the interval and repeat count flexible. 

Upvotes: 3

Related Questions