Search code examples
iosobjective-cnsdecimalnumber

Why does this Creation of NSDecimalNumber crash?


I am downloading some values from a cloud service as JSON objects and assigning them to NSString objects as below

NSString *price = [orpObjectDict objectForKey:@"price"];
NSString *qty = [orpObjectDict objectForKey:@"qty"];

My debug output shows that both strings have values as below

NSLog(@"price: %@ <--> qty: %@", price, qty);

2017-04-17 16:29:05.665043 NWMobileTill[1490:730225] price: 6.95 <--> qty: 1

But the following creation of NSDecimalNumber using those NSStrings fail

NSDecimalNumber *priceNumber = [NSDecimalNumber decimalNumberWithString:price];
NSDecimalNumber *qtyNumber = [NSDecimalNumber decimalNumberWithString:qty];

017-04-17 16:29:05.665886 NWMobileTill[1490:730225] -[__NSCFNumber length]: unrecognized selector sent to instance 0x174226240
2017-04-17 16:29:05.668080 NWMobileTill[1490:730225] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber length]: unrecognized selector sent to instance 0x174226240'
*** First throw call stack:
(0x1926fd1b8 0x19113455c 0x192704268 0x192701270 0x1925fa80c 0x19323658c 0x1932340f0 0x193234754 0x1000d9078 0x192cff1e8 0x192d17120 0x1931ebfb0 0x193130aa8 0x1931210a4 0x1931ee35c 0x1006c5218 0x1006d2aec 0x1006c8ce0 0x1006d4e2c 0x1006d4b78 0x19178f2a0 0x19178ed8c)
libc++abi.dylib: terminating with uncaught exception of type NSException

Why is this simple creation crashing?


Solution

  • You are getting Number and you are write code as string

    Please write as this code in string formate

     NSString *price = [NSString stringWithFormat:@"%@", orpObjectDict objectForKey:@"price"];
     NSString *qty = [ [NSString stringWithFormat:@"%@",orpObjectDict objectForKey:@"qty"];
    

    or simply check

    if [price isKindOfClass:[NSString class]]
    {  // It is string
    }
    else if [price isKindOfClass:[NSNumber class]]
    {
      // It is number
    }