I've written an iPhone App that calculates a total cost by adding/subtracting units of predetermined cost. This was working fine until I realised that the float values I was using caused the total to be inaccurate so I started to look into using NSDecimalNumber. I'm now rather confused and have an 'out of scope' error. Relevant sections of my (simplified) code are below. How can I get this to work as expected?
MyViewController.h
#import <UIKit/UIKit.h>
@interface MyViewController : UIViewController {
IBOutlet UILabel *totalPrice;
NSDecimalNumber *total;
NSDecimalNumber *item1Price;
}
@property (retain, nonatomic) NSDecimalNumber *total;
@property (retain, nonatomic) UILabel *totalPrice;
- (IBAction)addItem:(id)sender;
- (void)getDefaults;
- (void)setLabels;
@end
MyViewController.m
#import "MyViewController.h"
@implementation MyViewController
@synthesize total;
@synthesize totalPrice;
- (void)getDefaults {
NSString *path = [[NSBundle mainBundle] pathForResource:@"prices" ofType:@"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
total = [NSDecimalNumber decimalNumberWithString:@"0"];
item1Price = (NSDecimalNumber *)[dict valueForKey:@"item1"];
}
- (void)setLabels {
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[numberFormatter setCurrencySymbol:@"£"];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
totalPrice.text = [numberFormatter stringFromNumber:total];
}
- (void)viewDidLoad {
[self getDefaults];
[self setLabels];
}
- (IBAction)addItem:(id)sender {
NSDecimalNumber *itemPrice;
switch ([sender tag]) {
case 1:
itemPrice = item1Price;
break;
}
total = [total decimalNumberByAdding:itemPrice];
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[numberFormatter setCurrencySymbol:@"£"];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
totalPrice.text = [numberFormatter stringFromNumber:total];
}
@end
I'm hoping that I'm on the right path...