【问题标题】:NSUserDefaults display date and data in the tableViewNSUserDefaults 在 tableView 中显示日期和数据
【发布时间】:2012-10-27 10:14:20
【问题描述】:

在我的调查应用程序的 FirstViewController 中,我有包含数据(字符串)的 NSMutableArray。我还创建了日期变量。这是代码

NSDateFormatter *dateformater=[[NSDateFormatter alloc] init];
[dateformater setDateFormat:@"EEEE,dd MMMM yyyy HH:mm a"];

NSDate *today=[NSDate date];
NSString *currentDate=[dateformater stringFromDate:today];

现在我想在 NSUserDefaults 的帮助下保存数组中的数据,并在进行调查时保存日期变量并将其显示在 SecondViewController 的表格视图中(第一个用户可以查看调查日期,然后点击日期 -数组中的数据)。

我知道 NSUSerDefaults 是如何工作的,但我不知道如何按日期变量放置数组以显示在 SecondViewController 中。谁能帮我解决这个问题?

【问题讨论】:

    标签: iphone nsstring nsdate tableview nsuserdefaults


    【解决方案1】:

    AppDelegate.h 文件中只声明变量...

    NSUserDefaults  *userDefaults;
    NSMutableArray *arrDate;
    

    之后……

    AppDelegate.m 中填充applicationDidFinishLonching: 方法

        userDefaults = [NSUserDefaults standardUserDefaults];
        NSData *dataRepresentingtblArrayForSearch = [userDefaults objectForKey:@"arrDate"];
        if (dataRepresentingtblArrayForSearch != nil) {
            NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingtblArrayForSearch];
            if (oldSavedArray != nil)
                arrDate = [[NSMutableArray alloc] initWithArray:oldSavedArray];
            else
                arrDate = [[NSMutableArray alloc] init];
        } else {
            arrDate = [[NSMutableArray alloc] init];
        }
        [arrDate retain];
    

    之后,当您想从此 UserDefaults 插入、更新或删除数据时,请使用波纹管代码...

    用于从数组中删除记录

    [appDelegate.arrDate removeObjectAtIndex:Index];/// give the integer value instead of Index
        
    

    这是用于在数组中添加记录..

    [appDelegate.arrDate addObject:currentDate];///add value or add date here
    

    在最终将修改保存在数组中之后,就像下面这样存档..

    NSData *data=[NSKeyedArchiver archivedDataWithRootObject:appDelegate.arrDate];
    [appDelegate.userDefaults setObject:data forKey:@"arrDate"];
    [appDelegate.userDefaults synchronize];
    

    【讨论】:

      【解决方案2】:

      使用日期和数据对象创建NSDictionary

      NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%@",currentDate], @"date", @"yourData", @"data", nil];

      然后将其放入NSUserDefault 使用:

      [NSUserDefaults standardUserDefaults] setObject:yourDictionary forKey:@"item1"];
      

      这会将单个数据存储到 NSUserDefault。

      您可以使用以下方法检索对象:

      NSDictionary * dictionary = [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"item1"];
      

      现在您将使用 [dictionary objectForKey:@"date"]; 获取日期,使用 [dictionary objectForKey:@"data"]; 获取数据

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-03
        • 1970-01-01
        • 2016-03-02
        • 2012-05-17
        • 2017-11-13
        • 1970-01-01
        相关资源
        最近更新 更多