ios - 显示一个 u int。当值为 0 时减去 1,我得到一个正数

标签 ios objective-c

我得到了一个定时器的无符号整数。但是当我在值为零时减去它的 1 时,它显示一个正数。像这样:http://prntscr.com/2wkydb . 这是我的代码 Viewcontroller.m:

-(IBAction)btnUp:(id)sender
{
    timer = timer + 1;
    lblTimer.text = [NSString stringWithFormat:@"%u", timer];
}
-(IBAction)btnDown:(id)sender
{
    timer = timer - 1;
    lblTimer.text = [NSString stringWithFormat:@"%u", timer];
}
-(IBAction)btnRestart:(id)sender
{
    lblTimer.text = [NSString stringWithFormat:@"0"];
}

Viewcontroller.h:

@interface ViewController : UIViewController
{
    unsigned int timer;
    IBOutlet UILabel *lblTimer;
}
-(IBAction)btnUp:(id)sender;
-(IBAction)btnDown:(id)sender;
-(IBAction)btnRestart:(id)sender;

@end

我需要做什么才能不显示正数但计时器保持为 0? 提前致谢。

编辑:我也不希望计时器显示负值。

最佳答案

无符号整数“环绕”。从零中减去 1 给出(假设 32 位整数):

0xFFFFFFFF = 4294967295

如果您不希望这样,请将您的代码更改为:

if (timer > 0)
    timer = timer - 1;

更好的是,当值达到零时禁用“向下”按钮,然后启用 当值为正时再次出现。

类似于(未经测试,未经编译器检查):

-(IBAction)btnUp:(UIButton *)sender
{
    timer = timer + 1;
    lblTimer.text = [NSString stringWithFormat:@"%u", timer];
    self.downButton.enabled = YES;
}
-(IBAction)btnDown:(UIButton *)sender
{
    timer = timer - 1;
    lblTimer.text = [NSString stringWithFormat:@"%u", timer];
    sender.enabled = (timer > 0);
}

关于ios - 显示一个 u int。当值为 0 时减去 1,我得到一个正数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22097689/

相关文章:

ios - 更改嵌套 NSMutableDictionary 中的值

ios - 将 Sprite Kit Physics Body 移动到用户触摸的位置而不通过

ios - 如何根据设备大小和比例调整 UIImage 的大小?

objective-c - 在 objective-c 中存储单词列表

iphone - 蓝牙可以与 iOS 多任务一起使用吗?

objective-c - 当 xcode 中的设备方向发生变化时,我将如何加载 xib?

android - NativeBase - ReactNative - 下拉列表

ios - 如何在 iOS 中画一枚硬币(一个灰色圆圈,上面有黑色文字)?

iphone - 带有特定地点路线的离线 map

iphone - 理解属性访问概念时遇到问题