Reputation: 1
I'm really stuck adding these values together. They both come from a .plist. Both are numbers. I want to add the values together and display the result as a string in a label.
NSInteger calories = [[self.Main objectForKey:@"calories"] integerValue];
NSInteger calories2 = [[self.apps objectForKey:@"calories"] integerValue];
I want to basically go with
NSString *totalCalories = calories + calories2;
self.calorieLabel.text = totalCalories;
But that does not work. I'm new to this and feel like I'm missing something small and obvious.
Any insight?
Upvotes: 0
Views: 120
Reputation: 23053
@bdesham is right, you can not directly add strings for mathematical operations like add/subtract. Yes some languages do support these kind of operations for strings.
In Objective C, you need to do conversation to specific type before do so. Above all answers will gives you correct result. Here i provide you to obvious way to do that conversation for number operations.
NSNumber *caloriesValue = [self.Main objectForKey:@"calories"];
NSNumber *caloriesValue2 = [self.apps objectForKey:@"calories"];
NSInteger totalCalories = [caloriesValue integerValue] + [caloriesValue2 integerValue];
NSString *totalCaloriesText = [NSString stringWithFormat:@"%ld", totalCalories];
Upvotes: 0
Reputation: 1023
juste create a string based on the result.
NSString *totalCalories = [NSString stringWithFormat:@"%i", calories + calories];
Upvotes: 0
Reputation: 5209
Adding two numbers return numbers, so you'll need to convert your number to NSString, for that you need NSString's stringWithFormat method :
NSString *totalCalories = [NSString stringWithFormat:@"%d", (calories + calories2)];
self.calorieLabel.text = totalCalories;
Upvotes: 0
Reputation: 16089
You’re already there as far as the addition itself:
NSInteger totalCalories = calories + calories2;
Now you need to convert this number to a string, which you can do like this:
NSString *totalCaloriesText = [NSString stringWithFormat:@"%d", totalCalories];
The problem was that you were trying to treat an integer expression (calories + calories2
) as a string. This is a valid thing to do in some programming languages, but in Objective-C you have to be explicit about such conversions.
Upvotes: 3