【问题标题】:Save new Variable Value [closed]保存新的变量值[关闭]
【发布时间】:2013-02-22 00:32:32
【问题描述】:

我有一个值为零的全局变量,然后我使用此代码更改值并放入标签:

- (IBAction)costSST
{
    // add cost to global variable "totalCost"
    float sstCost = totalCost + 3.50;
    self.lblcurCost.text = [NSString stringWithFormat:@"%.02f",  sstCost];
}

但是,我不知道如何保持全局变量的新值——在本例中为 3.50——而不是仍然为 0。有什么建议吗?提前致谢。

【问题讨论】:

  • 等等,totalCost 没有保值,还是 sstCost 没有保值?
  • @CodaFi 总成本没有保留其 3.50 的新值
  • 那是因为您没有设置 totalCost,而是设置了 sstCost。
  • @CodaFi 我在我的 m 文件中将 totalCost 设置为 0,但是当我执行操作 costSST 时,我希望总成本的值更改为 3.50
  • 你的意思是totalCost = 3.5; ?为什么代码中没有?

标签: iphone objective-c xcode macos cocoa-touch


【解决方案1】:

要使totalCost 保留它的值,您必须实际设置它的值,而不是在算术中引用它:

- (IBAction)costSST
{
    // add cost to global variable "totalCost"  Because of that, sstCost is unnecessary
    totalCost = 3.50f;
    self.lblcurCost.text = [NSString stringWithFormat:@"%.02f",  totalCost];
}

【讨论】:

    【解决方案2】:

    您不应该使用“全局变量”。将持久值存储在实例变量中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 2015-05-07
      • 1970-01-01
      • 2013-08-10
      相关资源
      最近更新 更多