2014-10-09 72 views
0

我真的坚持将这些值加在一起。他们都来自.plist。两个都是数字。我想将这些值加在一起,并将结果作为字符串显示在标签中。如何将这两个值一起添加到目标c

NSInteger calories = [[self.Main objectForKey:@"calories"] integerValue]; 
NSInteger calories2 = [[self.apps objectForKey:@"calories"] integerValue]; 

我想基本上与

NSString *totalCalories = calories + calories2; 
self.calorieLabel.text = totalCalories; 

走但不起作用。我对此很陌生,觉得我错过了一些小而明显的东西。

任何见解?

回答

3

你已经在那里,只要加入本身:

NSInteger totalCalories = calories + calories2; 

现在你需要这个号码转换为字符串,你可以这样做:

NSString *totalCaloriesText = [NSString stringWithFormat:@"%d", totalCalories]; 

问题是你试图把一个整数表达式(calories + calories2)当作一个字符串。这在某些编程语言中是有效的,但在Objective-C中,您必须明确这些转换。

0

两数相加返回数字,所以你需要你的电话号码转换成的NSString,为你需要的NSString的stringWithFormat方法:

NSString *totalCalories = [NSString stringWithFormat:@"%d", (calories + calories2)]; 
self.calorieLabel.text = totalCalories; 
0

中庸之道创建基于结果的字符串。

NSString *totalCalories = [NSString stringWithFormat:@"%i", calories + calories]; 
0

@bdesham是对的,你不能直接添加字符串进行数学运算,如加/减。是的,有些语言确实支持这些字符串操作。

在目标C中,您需要先进行与特定类型的对话。 以上所有答案都会给你正确的结果。在这里,我向你提供了明显的方式来进行号码操作的对话。

NSNumber *caloriesValue = [self.Main objectForKey:@"calories"]; 
    NSNumber *caloriesValue2 = [self.apps objectForKey:@"calories"]; 

    NSInteger totalCalories = [caloriesValue integerValue] + [caloriesValue2 integerValue]; 
    NSString *totalCaloriesText = [NSString stringWithFormat:@"%ld", totalCalories]; 
相关问题