Search code examples
objective-cnsdecimalnumber

Why does this NSDecimalNumber from NSString assignment fail?


I have a very simple piece of code that crashes when setting the NSDecimalNumber.

the code looks like this

NSDecimalNumber *price = nil;
NSString *variantPrice = nil;
variantPrice = fcVariantRow[@"fcVariantPrice"];
price = [NSDecimalNumber decimalNumberWithString:variantPrice];

It crashes when assigning the value to variable price with the following crash info

2017-12-20 15:26:11.523917+0800 NWMPos[28837:18554790] -[__NSCFNumber 

length]: unrecognized selector sent to instance 0xb000000000000635
2017-12-20 15:26:11.525159+0800 NWMPos[28837:18554790] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber length]: unrecognized selector sent to instance 0xb000000000000635'
*** First throw call stack:
(0x187151d04 0x1863a0528 0x18715f1c8 0x1871576b0 0x18703d01c 0x187b6ceac 0x187b6aa38 0x187b6b0a0 0x1041131a0 0x1905bd608 0x1905bd588 0x104d9f83c 0x104d9d438 0x1905bd608 0x1905bd588 0x1905a82f0 0x1905bce7c 0x1905bc99c 0x1905b7e6c 0x190589378 0x190ed685c 0x190ed8de8 0x190ed1d04 0x1870fa2e8 0x1870fa268 0x1870f9af0 0x1870f76c8 0x187017fb8 0x188eaff84 0x1905ec2e8 0x1041151e8 0x186b3a56c)
libc++abi.dylib: terminating with uncaught exception of type NSException

The debugs shows me that the NSString has a correct value as follows

017-12-20 15:26:11.523626+0800 NWMPos[28837:18554790] Jongel 4 = 99

99 is the value of the NSString

Why is this crashing?


Solution

  • fcVariantRow[@"fcVariantPrice"] returns NSNumber type.
    

    just use

    price = (NSDecimalNumber*) fcVariantRow[@"fcVariantPrice"];