0

I have an iOS app where everytime the user clicks he or she gains 10 points. I have a label that displays the users points that updates every time points are gained. This is difficult to phrase, but my question is how I would make this counter show every number that gets added?

Example:

What I have right now: User clicks. Counter displays 10. User clicks again. Counter displays 20. So on and so on

What I am trying to do: User clicks. Counter goes 1,2,3,4,5,6,7,8,9,10 all in one second.

Hopefully you can understand my question!

Thanks in advance!

DrummerB
  • 39,814
  • 12
  • 105
  • 142
Albert K
  • 25
  • 7
  • Either use an NSTimer or recursively call a method that adds one to the label's text until it reaches the next multiple of 10. – rdelmar Mar 01 '14 at 01:48
  • You mean, animate the increase? Well, I think you can use an NSTimer (http://stackoverflow.com/questions/1449035/how-do-i-use-nstimer) to schedule a callback every (1.0 / pointsAcquired) to increase the timer by 1. – Saturn Mar 01 '14 at 01:49

2 Answers2

0

Something like this should work:

int count = ... // the current count
for (int i = 1; i <= 10; i++) {
    dispatch_async(dispatch_get_main_queue(), ^{
        someLabel.text = [NSString stringWithFormat:@"%d", count + i];
    });
}
count += 10;

But this might change the count too fast. There will be virtually no delay between each update.

The following will take roughly 1 second to update the number:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timeout * NSEC_PER_SEC), dispatch_get_local_queue(), ^{
int count = ... // the current count
for (int i = 1; i <= 10; i++) {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, i * 0.1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        someLabel.text = [NSString stringWithFormat:@"%d", count + i];
    });
}
count += 10;
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • That works well, thank you. The problem is though, that the user can buy upgrades that automate the process of receiving points. This means that I have an NSTimer that fires every second that gives the user a variable number of points. I've been working trying to get your code accustomed to my system so that it doesn't get left too far behind or go too far. If you have any suggestions I would really appreciate them, since I'm quite new to objective-c. – Albert K Mar 01 '14 at 02:42
  • I'd suggest closing out this question and create a new question specific to your new issue. – rmaddy Mar 01 '14 at 03:17
0

Starting with a label showing 0, this should work,

- (IBAction)incrementLabel:(id)sender {
    self.label.text = [NSString stringWithFormat:@"%d", self.label.text.integerValue + 1];
    [self performSelector:@selector(incrementLabel:) withObject:self afterDelay:.1];
    if (self.label.text.integerValue % 10 == 0) [NSObject cancelPreviousPerformRequestsWithTarget:self];
}
rdelmar
  • 103,982
  • 12
  • 207
  • 218