【问题标题】:Calculation returns after second press on button第二次按下按钮后计算返回
【发布时间】:2014-08-01 15:43:35
【问题描述】:

我是 Objective C 的新手。我在创建单位转换应用程序时遇到了问题。这是有问题的代码(PS 我知道这不是正确的转换):

问题是,当我按下转换按钮时,它会返回初始化值 0。然后我必须再次按下按钮才能获得我的计算值。谢谢。

当然,我是个大菜鸟,这是我的第一天 :)。

-(IBAction)convert:(id)sender{

int unitType;
double unitTemp1 = [_tempField.text doubleValue];
double unitTemp2 = 0;

switch(unitType)
{
    case 1:
        //Celcius to Farenheight
        NSLog(@"Celcius to Farenheight Selected");
        unitTemp2 = unitTemp1*9;
    break;
}

if([_array objectAtIndex:1])
{
    unitType = 1;
}


NSString* resultString = [[NSString alloc] initWithFormat:@"%f",unitTemp2];
_tempResult.text = resultString;
//initwithformat
}

【问题讨论】:

  • 该方法执行时,unitType没有初始化,可以是任意随机值。所以不知道你的 switch() 语句将如何表现,总是在 Obj C 中初始化你的变量。

标签: objective-c xcode ios7 xcode5


【解决方案1】:

因为你在 switch 之后设置了unitType,所以解决方法是移动上面的代码,并为你的 switch 提供一个默认值

int unitType = 0;

if([_array objectAtIndex:1])
{
    unitType = 1;
}


switch(unitType)
{
    case 1:
        //Celcius to Farenheight
        NSLog(@"Celcius to Farenheight Selected");
        unitTemp2 = unitTemp1*9;
    break;
    default:
        //match anything else
        NSLog(@"Celcius to Farenheight not Selected");
    break;

}

【讨论】:

  • 好吧,我不是那种乞求点赞的人,我在你之前发过帖子,而我在编辑的时候,你来提出同样的观点,然后抱怨。
  • @PanoKatsourakis Meda 的“2014 年 8 月 1 日 15:48 回答” - 你的“14 年 8 月 1 日 15:50 回答” - 很明显,他的回答早了 2 分钟。很多水可以在 2 分钟内流过桥下 ;-) 时间戳不会说谎。
  • 哈哈@Fred-ii- 正是兄弟,这个网站上发生了疯狂的事情哈哈
  • @meda - 更疯狂的事情将继续发生 - 干杯 ;-) 我希望你一切都好,兄弟。
  • lol je suis un man, j'espere que toi aussi je t'ai appeler bro a quelque reprise now, ok remove them now :P
【解决方案2】:

尝试将 if 语句向上移动,以便在 switch 语句之前将其初始化为一个值

int unitType;

if([_array objectAtIndex:1])
{
    unitType = 1;
} else
{ 
    unitType = 0;
}

【讨论】:

    猜你喜欢
    • 2020-01-23
    • 2013-07-13
    • 2014-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-09
    相关资源
    最近更新 更多