0

Imagine the following code:

    NSMutableArray *arr = [NSMutableArray arrayWithObjects:@200, @100, nil];
    
    NSInteger n1 = (NSInteger)[arr objectAtIndex:0];
    NSInteger n2 = (NSInteger)[arr objectAtIndex:1];
    NSInteger r = n1 + n2;
    
    NSLog(@"n: %lid", r);

The result I am getting is: -4309586476825365866d, the expected one is: 300.

I also tried to evaluate the individual expressions in debugger to check what I am getting when reading the values from the array, like this: po (NSInteger)[arr objectAtIndex:0]. This showed the correct number, yet when trying to sum them both: po (NSInteger)[arr objectAtIndex:0] + (NSInteger)[arr objectAtIndex:0], an invalid result is generated.

Any ideas why? I am very new to Objective-C, so any source where I could get more info about the issue is appreciated.

1
  • 1
    The NSArray can only hold objects: namely NSNumbers. -objectAtIndex: returns the pointer to the number; casting it to an NSInteger isn't what you want to do. Instead, use [[arr objectAtIndex:0] integerValue]; Commented Dec 25, 2021 at 21:28

1 Answer 1

1

You cannot cast NSNumber to NSInteger. You have to call integerValue.

And for more than 10 years there is a more convenient array literal syntax as well as a more convenient index subscription syntax

NSArray *arr = @[@200, @100];

NSInteger n1 = [arr[0] integerValue];
NSInteger n2 = [arr[1] integerValue];
NSInteger r = n1 + n2;

NSLog(@"n: %ld", r);

And for the string format use either i or d but not both.

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

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.