自动减少NSNumber本身-1

时间:2014-10-03 11:36:09

标签: ios sleep void nsnumber viewdidload

好的,基本上,我正在尝试构建一些允许NSNumber每分钟减少1的代码,

这是我到目前为止所做的。

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

首先,它不会每分钟减少一个,其次是numVar中的初始viewDidLoad是错误的吗?

4 个答案:

答案 0 :(得分:2)

我们尝试了这个,它可以满足我们的需求: 您需要在代码中重新安排此操作

- (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 
    }

}

答案 1 :(得分:1)

您在主线程内部睡眠,阻止您的UI。您需要使用NSTimer或类似的计时机制来定期运行该功能而不会阻塞。

答案 2 :(得分:0)

@implementation YourViewController 
{
    NSNumber *numVar;
}    

- (void)viewDidLoad 
{
    [super viewDidLoad];    
    numVar = [NSNumber numberWithUnsignedChar:99];
    [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
}

- (void)timerFireMethod:(NSTimer *)timer
{
    numVar = [NSNumber numberWithInt:[numVar intValue] - 1];
}

答案 3 :(得分:0)

每当我需要快速的东西时,我都会这样做

- (void)viewDidLoad 
{
    [super viewDidLoad];
    [self performSelector:@selector(num) withObject:nil afterDelay:60];
}

- (void)num
{
    NSNumber *numVar = [NSNumber numberWithUnsignedChar:numVar-1];
    [self performSelector:@selector(num) withObject:nil afterDelay:60];
}

你可以在一分钟之后再决定你想要再做一次的num函数。