已保存的数据将被应用重新启动时的新数据所取代

时间:2013-11-06 02:17:59

标签: ios

我正在制作一个卡路里计数器,显示添加的各种食物的总卡路里计数。我编写了代码来保存此tutorial之后的数据。当我重新启动应用程序时,我可以看到卡路里计数与我退出应用程序时的卡路里计数相同但是当我添加新的食物项目时,卡路里计数被重置并且计数从开始开始。为什么没有保存这个值?

编辑:

这是我的代码片段:

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];

}

0 个答案:

没有答案