how should nsdecimalnumber's be stored in the database?
What is the best way to store nsdecimalnumbers in a database? Numeric types like float, real and double are out, because it is important to preserve the precision for currency usage.
The two alterna开发者_StackOverflow中文版tives I have considered are string and storing two ints, one holding the mantissa and one holding the exponent. The challenge facing the latter approach is that I dont see an easy way to pull the mantissa and exponent out of the nsdecimalnumber. I can get NSDecimal from NSDecimalNumber, but the mantissa and exponent properties seem to be private! Perhaps I can reverse number = (mantissa * 10^exponent), but is there a better way to do this?
The requirement I have is that I would need to perform some aggregate sum operations on this field in the database. If I store as a string, perhaps performing this calculation would be more difficult. I would still need to write a custom function to sum over a mantissa and exponent in the database, so maybe its still as heavy.
Edit: I can access the exponent, but the mantissa is kept in a weird manner...poking at it in the debugger reveals that it is an array of short(ints).
NSDecimalNumber conforms to NSCoding, so you could encode it with encodeWithCoder:
before adding it to your database, and then decode it using initWithCoder:
when retrieving it from the database.
See the Archives and Serializations Programming Guide, specifically "Encoding and Decoding Objects" for more details on using encoders.
精彩评论