Mehul Solanki
Mehul Solanki

Reputation: 463

NSTimer not working well for UITableviewCell

I have to create something like, there is UITableView which have much multiple rows with multiple sections and every row has different Timer showing in 'hh:mm:ss' format and it decrementing every second, just like countdown.

I'm getting problem that when i scroll UITableView, few UILabels re-initialised and countdown time gone and even it gets over-rides for few cells. I'm using following code to achieve my requirement :

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

       //Somewhere, in this method
       elapsedTimeTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(runningTimer:) userInfo:dic repeats:YES];

       [[NSRunLoop currentRunLoop] addTimer:elapsedTimeTimer
                                         forMode:NSRunLoopCommonModes];
}

-(void)runningTimer:(NSTimer *)timer {
       secondsLeft --; //I'm able to get seconds 

       hours = secondsLeft / 3600;
       minutes = (secondsLeft % 3600) / 60;
       seconds = (secondsLeft %3600) % 60;

       cell.lblTime.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
}

Please help me for solving this problem. Any kind of help, will surely appreciated.

Thanks.!!..

Upvotes: 0

Views: 1120

Answers (2)

Miknash
Miknash

Reputation: 7948

You need to have an array of elements or dictionary to keep track of your timers.

Every cell in uitableview is reused and since your timers will be affected.

Instead of elapsedTimeTimer I would use

elapsedTimeTimers[indexPath.row]

Where elapsedTimeTimers is array of timers.

Ofcourse, this applies if you have one section. If you have more then you will have to calculate correct index. Also, if you have an object to keep all this data, you could use objects id or something like that.

Upvotes: 2

Mustafa Ibrahim
Mustafa Ibrahim

Reputation: 1120

You must not create the timer object inside cellforRowatIndex. it will create too many timers objects as the datasource count. just create the timer once in viewDidLoad, viewWillAppear or even after you set your datasource. I think your issue is you have scheduled more than one timer and all is fired.

Good Luck

Upvotes: 1

Related Questions