【问题标题】:Attempting a more-than if statement causes crash [closed]尝试超过 if 语句会导致崩溃 [关闭]
【发布时间】:2014-03-12 13:42:37
【问题描述】:

我对 iOS 开发很陌生,问这个问题我可能看起来像个白痴。 但尝试此操作会使应用完全崩溃。

- (IBAction)action:(id)sender
{
    if(NSInteger >= 4) {
        timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                 target:self selector:@selector(countup)userInfo:nil repeats:YES];
        NSLog(@"Action: ‘action' succeeded");
    }
    else
    {
        [screen setText:[NSString stringWithFormat:@“You cannot do this."]];
        NSLog(@"Action: ‘action' failed");
    }
}

计数定义为:

- (void)countup
{
    NSInteger += 1;
    [screen setText:[NSString stringWithFormat:@"Seconds: %d", NSInteger]];
}

我不知道自己做错了什么,我已经尝试修复了几个小时,但找不到任何对我有帮助的答案。

【问题讨论】:

  • NSInteger >= 4 & NSInteger += 1: NSInteger,这是变量名?
  • 它们的值相同
  • 我认为这段代码根本没有运行。
  • @StevenM NSInteger += 1 应该是 NSInteger myInt +=1 并且你应该遵循整个应用程序 NSInteger 是类型 myInt 是你可以操作的实际变量。
  • @sbarow:如果这是应用程序无法编译的原因。但 OP 声称它崩溃。 - (顺便说一句,你可以调用变量NSInteger,这并不意味着你应该!

标签: ios objective-c if-statement


【解决方案1】:

我假设您至少具备一些其他语言的计算机编程知识,然后是 Objective-C。

我会讲这一行,但同样的问题出现在你的代码中的几行

if(NSInteger >= 4)

您将类型 NSInteger 与一个数字 (4) 进行比较。我假设您想将 NSInteger 类型的变量与数字 4 进行比较!

因此,您的代码将如下所示:

NSInteger mySavedNumber = 20;
if(mySavedNumber >= 4)

办公室。 'mySavedNumber' 是我随机选择的变量的名称,您可能应该将其更改为对您有意义的东西,但我不知道您的其余代码,我真的不知道您想要做什么.但是你不能把它命名为 NSInteger,因为 'NSInteger' 是一个已经被占用的名字。

出于同样的原因,这行代码也行不通:

NSInteger += 1;

同样,NSInteger 只是一个类型,而不是变量本身。

【讨论】:

  • 如果这是应用程序无法编译的原因。但 OP 声称它崩溃。 - (顺便说一句,你可以调用变量NSInteger,这并不意味着你应该!
【解决方案2】:

你需要使用一个变量。

NSInteger x;

然后

if (x >= 4) ...
[NSString stringWithFormat:@"Seconds: %d", x] ...

【讨论】:

    【解决方案3】:

    NSInteger 是类型而不是变量。 你应该有NSInteger myInt 和使用myInt

    if(myInt >= 4)
    

    myInt++;
    

    【讨论】:

      【解决方案4】:

      老兄,你需要创建一个 NSInteger 类型的变量。创建一个变量,然后使用它代替 NSInteger。

      修改代码

      -(IBAction)action:(id)sender
      {
          NSInteger num;
      
          if(num >= 4) {
              timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countup)userInfo:nil repeats:YES];
      
              NSLog(@"Action: ‘action' succeeded");
          }
          else {
              [screen setText:[NSString stringWithFormat:@“You cannot do this."]];
      
              NSLog(@"Action: ‘action' failed");
          }
      }
      
      -(void)countup
      {
          num += 1;
          [screen setText:[NSString stringWithFormat:@"Seconds: %d", num]];
      }
      

      【讨论】:

        猜你喜欢
        • 2014-08-12
        • 1970-01-01
        • 2015-03-29
        • 2021-03-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多