0

I have a NSMutableArray, containing x different NSStrings (NSString but only numbers no letters). I would like to add up all of the values to return a single float, or int. I think I have to do this with a for loop, but i am very unfamiliar with for loops.... OK I have reached this point:

for (NSString *a in det) 
{
   float x = [a floatValue];
   NSLog(@"%.2f",x);
}

And this returns all the values like this in ´NSLog`:

23.00
8.00
61.00
...

How could i just add them up now?

4 Answers 4

14

You can avoid looping and instead use the key value coding and obtain the total

    NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"1.1", @"2.2", @"3.1", nil];
    NSNumber *sum = [arr valueForKeyPath:@"@sum.floatValue"];

Variable sum will be 6.4.

Sign up to request clarification or add additional context in comments.

2 Comments

I like this. I’m using this technique to see if a user preference has any values selected. I use ---- NSNumber *total1=[prefsCategory1 valueForKeyPath:@"@sum.intValue"]; --- then --- convert it to an int in my conditional ---- if ( [total1 unsignedIntegerValue] > 0 ) {
Great answer, +1, i was just suffering answer and found good use of KVC.
5

Try this:

float total = 0;
for(NSString *str in det)
{
    total += [str floatValue];
}

1 Comment

rats...looks like you beat me to this one =)
3

Here is the code for a for-in if you want to save a bit of typing. It's preferable to use fast enumeration for these types of scenarios with data structures that support it.

float result = 0.0;
for(NSString *i in nsArray)
{
    result += [i floatValue];
}

Comments

2
int result = 0;

for(int i=0;i<[array count];i++) 
     result += [[array objectAtIndex:i] intValue];

if you need to return a float simply define result as float and use floatValue instead of intValue

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.