J'ai écrit une application iPhone qui calcule un coût total en ajoutant/soustrayant des unités de coût prédéterminé. Cela fonctionnait bien jusqu'à ce que je me rende compte que les valeurs flottantes que j'utilisais rendaient le total inexact. J'ai donc commencé à chercher à utiliser NSDecimalNumber. Je suis maintenant assez confus et j'ai une erreur 'out of scope'. Les sections pertinentes de mon code (simplifié) sont ci-dessous. Comment puis-je faire en sorte que cela fonctionne comme prévu ?
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
J'espère que je suis sur la bonne voie...