0

I want two take the values at index 0 from two separate arrays and combine them together. For example, let's say the value at index 0 for array1 is NSNumber 5 and the value at index 0 for array2 is NSNUmber 7, how can I get a integer that says that the sum of the two values is 12? I'm just looking for a general answer but this is the code I have so far

NSNumber *j = [self.array1 objectAtIndex:0];
NSNumber *k = [self.array2 objectAtIndex:0];

I can't just simply add the two, but what do I have to do to allow me to add them?

2
  • Are the numbers integers, floats, etc? Commented Nov 17, 2013 at 1:58
  • j.integerValue will give you the integer value so you can add it. Commented Nov 17, 2013 at 1:58

2 Answers 2

3

If them are NSNumber and you want another NSNumber, you must to do:

NSNumber *n = [NSNumber numberWithInt:[[self.array1 objectAtIndex:0] intValue] + [[self.array2 objectAtIndex:0] intValue]];

Or using modern Objective C syntax, this can be shortened significantly.

NSNumber *n = @([self.array1[0] intValue] + [self.array2[0] intValue]);
Sign up to request clarification or add additional context in comments.

Comments

0

Assuming they're integers, you can use:

NSInteger result = [j integerValue] + [k integerValue];

See the NSNumber Class Reference if they're stored as other types.

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.