Ching Jui Young Ching Jui Young - 1 year ago 69
Swift Question

NSDecimalNumber.adding from NSManagedObjects hitting unrecognized selector issue

First, let me thank everyone in the SO community in advance for your help in getting me out of this jam.

My app hits a runtime error, and I've isolated the line causing the error.

When I attempt to add two NSDecimalNumber variables use the .adding method, I receive this "unrecognized selector sent to instance" error:

Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[__NSCFNumber
decimalNumberByAdding:]: unrecognized selector sent to instance

I've created dummy NSDecimalNumber variables to try and debug this issue, and they seem to work fine when adding. However, when working with my NSManagedObject variables (
) which have NSDecimalNumber variables, I run into this error.

Below is the code that is causing these issues:

//Testing with dummy variables
let a1 = NSDecimalNumber(decimal: 5.2)
let a2 = NSDecimalNumber(decimal: 10.8)

print ("a1: \(a1), a2: \(a2)") //a1: 5.2, a2: 10.8

let a3 = a1.adding(a2)

print ("a3: \(a3)") //a3: 16
//Great, everything above works fine.

//Now let's try using my NSManagedObjects, which were defined in another section
let a = result.netChange //result.netChange is of class NSDecimalNumber
let b = newTransaction.amount //newTransaction.amount is of class NSDecimalNumber

print ("a: \(a), b: \(b)") //a: 444.12, b: 22.23

let c = a.adding(b) //<---This is where the app crashes

print ("c: \(c)") //Does not print, as the app has stopped

My question: Why are my dummy variables able to add with each other, while my NSManagedObject variables cannot?

Thanks again!

Answer Source

A core data property of type "Double" is stored as NSNumber in the managed object context. It is not sufficient to change the type in the NSManagedObject subclass because the accessor methods are created dynamically at runtime. Your code compiles, but crashes at runtime because the variable is a NSNumber and not a NSDecimalNumber.

The solution is to set the type to "Decimal" in the Core Data model inspector.