SpokaneDude
SpokaneDude

Reputation: 4974

Why does this type conversion of NSString to NSNumber returns invalid value of -1?

This is the line of code in question:

bks.quantity = [NSNumber numberWithInteger: [[arrayOfSplitStrings[i] objectAtIndex:[[sd.dictionaryOfUserIndexes objectForKey: @"29"] intValue]] intValue]-1];

sd.dictionaryOfUserIndexes objectForKey: @"29" contains a string (representing a quantity) that has to be converted to NSNumber. When the statement is executed with a valid string quantity (0-10) it always returns -1, when it is supposed to return the NSNumber for the value.

What am I doing wrong?

Upvotes: 0

Views: 81

Answers (1)

Larme
Larme

Reputation: 26026

This is not a "straight forward" answer (since the solution is just a silly one), it's more a suggestion on work methods, that's why I post an answer.

It's not always good to put it various lines in a single line. Especially when in your case you encounter an issue. It's better to split each command, one by one, and to debug, check the value of each ones.

In your case:

bks.quantity = [NSNumber numberWithInteger: [[arrayOfSplitStrings[i] objectAtIndex:[[sd.dictionaryOfUserIndexes objectForKey: @"29"] intValue]] intValue]-1];

==>

NSInteger userOfIndexes = [[sd.dictionaryOfUserIndexes objectForKey: @"29"] intValue];
NSLog(@"userOfIndexes: %d", userOfIndexes);
NSInteger n = [arrayOfSplitStrings[i] objectAtIndex:userOfIndexes] intValue];
NSLog(@"n: %d", n);
bks.quantity = [NSNumberWithInteger:n-1];

I added NSLog(), but the values could be check with breakpoints and debugger. I could have also add a check on arrayOfSplitStrings with

NSArray *splitStrings = arrayOfSplitString[i];
NSLog(@"splitStrings: %@", splitStrings);

and replace n with:

NSInteger n = [splitStrings objectAtIndex:userOfIndexes] intValue];

That way, you would have check that apparently (according to your comment), your issue was were to put the "-1.

NSInteger n = [[arrayOfSplitStrings[i] objectAtIndex: userIndex-1] intValue];

Upvotes: 1

Related Questions