【问题标题】:iOS: Saving a date picker's settingsiOS:保存日期选择器的设置
【发布时间】:2012-01-19 23:20:50
【问题描述】:

我对内存管理非常陌生,我有一个关于保存日期选择器日期的问题。这是我用来保存输入文本的代码:

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

但我不确定如何将其加载到保存状态。抱歉,如果这些都是愚蠢的问题,我还是很新,我还在学习。

谢谢!

【问题讨论】:

    标签: ios xcode date uidatepicker picker


    【解决方案1】:

    持久化数据的最简单方法是使用 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];
    }
    

    【讨论】:

    • HereNSUserDefaults 的一个很好的可视化教程。
    • 太棒了,非常感谢马克!还有一个问题,我应该将 NSUserDefaults 的第一块代码放在 viewDidLoad 方法中的什么位置?
    • 这取决于您想要实现的用户体验。您的 UI 中可能有一些按钮来保存状态。您可以在按钮触发的操作中执行该操作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-21
    • 2023-03-07
    相关资源
    最近更新 更多