Search code examples
iossleepvoidnsnumberviewdidload

Reducing a NSNumber by itself-1, automatically


Ok so basically, I'm trying to build some code that allows an NSNumber to reduce by 1 every minute,

This is what I have so far.

- (void)viewDidLoad {
[super viewDidLoad];
NSNumber *numVar = [NSNumber numberWithUnsignedChar:99];
[self num];
}
-(void)num{
usleep(60000000);
NSNumber *numVar = [NSNumber numberWithUnsignedChar:numVar-1];
[self num];
}

First off, it won't reduce by one every minute and secondly is it wrong to have the initial numVar in viewDidLoad?


Solution

  • We tried this and it worked fine for what we needed : You need to re-arrange this in your code though

    - (void)viewDidLoad{
         NSTimer *timer;
         int minutes = 0;
    
         //Creating a label that shows the timer ; i assume you have one that is already linked
         _labelTimer.text = [NSString stringWithFormat:@"This is %i minute", minutes];
    
         //Creating the timer itself with the NSTimer object
         timer = [NSTimer scheduledTimerWithTimeInterval: 60.0 target: self selector:@selector(decreaseTimeCount) userInfo:nil repeats:YES];  
    
         //Note that 60 is the number of seconds before it calls the selector. You can use 1 if you want it to change your timer/clock every second
    }
    - (void)decreaseTimeCount{
    
        //The method changes the value of my variable and updates the label. If i'm at the 10th minute, i could do something, like perform a segue.
    
        minute+=1;
        _labTimer.text = [NSString stringWithFormat:@"This is %i minutes", minutes];
    
        if (minutes == 10){
            //do stuff 
        }
    
    }