Reputation: 3849
I'm trying to retrieve a number from user defaults and multiply it. Here's my code:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSDecimalNumber *current = [prefs objectForKey:@"account"];
NSDecimalNumber *multiplier = [NSDecimalNumber decimalNumberWithString:@"1.15"];
NSDecimalNumber *floo = [current decimalNumberByMultiplyingBy: multiplier];
It's giving me this really hideous crash as soon as it hits the floo
line. The huge spew of error gobbledygook begins with:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '-[__NSCFNumber decimalNumberByMultiplyingBy:]: unrecognized selector
sent to instance 0x8c7b1e0'
This seemed like a very simple thing, but my goodness! What's happening?
Upvotes: 0
Views: 1018
Reputation: 1713
Better may be to use an archiver, like storing the object as:
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:current] forKey:@"account"];
and retrieving it:
current = [NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] objectForKey:@"account"] ];
That is more reliable I think than seeing that you actually have an __NSCFNumber back, and converting that.
Upvotes: 0
Reputation: 17916
You've assigned the value of [prefs objectForKey:@"account"]
to an NSDecimalNumber variable, but the actual value is an NSNumber, not an NSDecimalNumber. When you try to call -decimalNumberByMultiplyingBy:
on that object, your program crashes, because that object doesn't know what to do with that method.
You can convert an NSNumber to an NSDecimalNumber like this:
NSNumber *number = /* ... */
NSDecimalNumber *decimalNumber =
[NSDecimalNumber decimalNumberWithDecimal:[number decimalValue]];
Upvotes: 5