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.
CodePudding user response:
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.