从文本字段读取整数错误

时间:2013-07-13 14:43:27

标签: ios uitextfield

我正在尝试更改UILabel,具体取决于哪个是4个文本字段的最高intValue。这是我的代码,但是当我输入和整数时,它完全错误地输出到控制台。例如,“1”打印为520387200

这是我的代码,任何关于我做错的想法都将不胜感激!谢谢!


    -(IBAction) upDateCalories{
        NSLog(@"Update Calories has been fired");

         if( [breakfast.text intValue] > [lunch.text intValue] && [dinner.text intValue] && [snacks.text intValue]) {

            MostCalorificMeal.text = @"Breakfast";
            NSLog(@"breakfast is highest");

        }


        else if( [lunch.text intValue]  >     [breakfast.text intValue] && [dinner.text intValue] && [snacks.text intValue])    {

            MostCalorificMeal.text = @"Lunch";
            NSLog(@"Lunch is highest");

        }     


       else if( [dinner.text intValue] >    [breakfast.text intValue] && [lunch.text intValue] && [snacks.text intValue]){

            MostCalorificMeal.text = @"Dinner";
            NSLog(@"Dinner is highest");

        }     

     else   if( [snacks.text intValue] >    [breakfast.text intValue] && [lunch.text intValue] && [dinner.text intValue]) {

            MostCalorificMeal.text = @"Snacks";
            NSLog(@"Snacks is highest");

        } 

        NSLog(@"breakfast %d",breakfast);
        NSLog(@"lunch %d",lunch);
        NSLog(@"dinne %d",dinner);
        NSLog(@"snacks %d",snacks);

    }

1 个答案:

答案 0 :(得分:1)

您要记录的值是UITextField类型的对象。您无法使用%d格式说明符记录UITextField

将您的日志更改为:

NSLog(@"breakfast %d@",breakfast.text);
NSLog(@"lunch %@",lunch.text);
NSLog(@"dinner %@",dinner.text);
NSLog(@"snacks %@",snacks.text);

您的if语句不正确。您无法使用该语法将一个值与其他几个值进行比较。你需要这样的东西:

if ([breakfast.text intValue] > [lunch.text intValue] && [breakfast.text intValue] > [dinner.text intValue] && [breakfast.text intValue] > [snacks.text intValue]) {
    // breakfast is the greatest
} else if ...

如果你使用了一些变量会更好:

int breakfastVal = [breakfast.text intValue];
int lunchVal = [lunch.text intValue];
int dinnerVal = [dinner.text intValue];
int snacksVal = [snacks.text intValue];

if (breakfastVal > lunchVal && breakfastVal > dinnerVal && breakfastVal > snacksVal) {
    // breakfast is the greatest
} else if ...

这样您就不会一遍又一遍地评估相同的值。