追加されたさまざまな食品の総カロリー数を表示するカロリーカウンターを作成しています。このチュートリアルに従って、データを保存するコードを作成しました。アプリを再起動すると、アプリを終了したときと同じカロリー数が表示されますが、新しい食品を追加すると、カロリー数がリセットされ、最初からカウントされます。値が保存されないのはなぜですか??
編集:
これは私のコードのスニペットです:
if(alertView.tag == ChickenAlertView) {
NSString *buttonTitle = [alertView buttonTitleAtIndex:buttonIndex];
if([buttonTitle isEqualToString:@"Ok"]){
float chicken= ([ChickenText.text floatValue]);
currentnumber = (chicken/100)*219;
result = result + currentnumber;
calories.text= [[NSString alloc] initWithFormat:@"%.f",result];
}
}
NSLog から、アプリを再起動するたびに結果の値が 0 になっていることがわかります。どうすれば防ぐことができますか?
これは私がコードを保存する場所です:
- (NSString *) saveFilePath {
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
return [[path objectAtIndex:0] stringByAppendingPathComponent:@"savefile.plist"];
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
NSArray *values = [[NSArray alloc] initWithObjects: NameLabel.text, AgeLabel.text, HeightLabel.text, WeightLabel.text, BMILabel.text, calories.text, [NSNumber numberWithFloat:result], nil];
[values writeToFile:[self saveFilePath] atomically:YES];
[values release];
}
- (void)viewDidLoad
{
foodData = [[foodData alloc]init];
NSString *myPath = [self saveFilePath];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:myPath];
if (fileExists)
{
NSArray *values = [[NSArray alloc] initWithContentsOfFile:myPath];
NameLabel.text = [values objectAtIndex:0];
AgeLabel.text = [values objectAtIndex:1]
HeightLabel.text = [values objectAtIndex:2];
WeightLabel.text = [values objectAtIndex:3];
BMILabel.text = [values objectAtIndex:4];
calories.text = [values objectAtIndex:5];
result = [[values objectAtIndex:6] floatValue];
[values release];
}
UIApplication *myApp = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationDidEnterBackground:)
name:UIApplicationDidEnterBackgroundNotification
object:myApp];
[super viewDidLoad];
}