iOS:保存日期选择器的设置

时间:2012-01-19 23:20:51

标签: ios xcode date uidatepicker picker

我对记忆管理很新,我对保存日期采摘日期有疑问。这是我用来保存输入文本的代码:

NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
    NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
    event1Field.text = [array objectAtIndex:0];
    event2Field.text = [array objectAtIndex:1];
}

如何编辑此项以保存日期选择日期而不是输入文字?我如何编辑viewDidLoad方法呢?我通常只在那里输入选择器的数据,如下所示:

- (void)viewDidLoad {
    NSDate *now = [NSDate date];
    [datePicker setDate:now animated:YES];
}

但我不确定如何将其加载到已保存状态。对不起,如果这些都是愚蠢的问题,我仍然很新,并且在我学习的过程中学习。

谢谢!

1 个答案:

答案 0 :(得分:3)

保留数据的最简单方法是使用Foundation框架提供的NSUserDefaults。它基本上只是一个键值存储,允许您保存少量数据。

首先,从日期选择器中保存数据看起来类似于:

// NSUserDefaults is a singleton instance and access to the store is provided 
// by the class method, +standardUserDefaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

// Let's pull the date out of our picker
NSDate *selectedDate = [self.datePicker date];

// Store the date object into the user defaults. The key argument expects a 
// string and should be unique. I usually prepend any key with the name 
// of the class it's being used in.
// Savvy programmers would pull this string out into a constant so that 
// it could be accessed from other classes if necessary.
[defaults setObject:selectedDate forKey:@"DatePickerViewController.selectedDate"];

现在,当我们想要将这些数据撤回并填充我们的日期选择器时,我们可以执行以下操作...

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Get the date. We're going to use a little shorthand instead of creating 
    // a variable for the instance of `NSUserDefaults`.
    NSDate *storedDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"DatePickerViewController.selectedDate"];

    // Set the date on the date picker. We're passing `NO` to `animated:` 
    // because we're performing this before the view is on screen, but after
    // it has been loaded.
    [self.datePicker setDate:storedDate animated:NO];
}