簡體   English   中英

如何收集兩個NSDictionary並添加到NSUserDefaults?

[英]How to gather two NSDictionary and add to NSUserDefaults?

我目前正在編程簽入應用程序。 我正在嘗試使用NSDictionary將所有簽入詳細信息收集到NSUserDefaults。 我有這個代碼塊;

NSMutableDictionary *oldcheckin =[[NSUserDefaults standardUserDefaults] dictionaryForKey:@"MissionID"];
            if([oldcheckin valueForKey:@"CheckinID"]) // I don't know how to take last object CheckinID value
            {
                int number = [[oldcheckin valueForKey:@"CheckinID"] intValue] +1;
                NSMutableDictionary *newcheckin= [[NSMutableDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%d",number], @"CheckinID",dateRightLabel.text, @"Date", noteLabel.text, @"Note",typeLabel.text, @"TypeID",projectLabel.text, @"ProjectID",noteLabel.text, @"Note", longitute, @"Longitute",latitude, @"Latitude",nil];
            }
            else
            {
                [[NSUserDefaults standardUserDefaults] setObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:@"1", @"CheckinID",dateRightLabel.text, @"Date", noteLabel.text, @"Note",typeLabel.text, @"TypeID",projectLabel.text, @"ProjectID",noteLabel.text, @"Note", longitute, @"Longitute",latitude, @"Latitude",nil] forKey:@"MissionID"];
                 NSDictionary * myDictionary = [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"MissionID"];
                 NSLog(@"%@",myDictionary);

            }
            [[NSUserDefaults standardUserDefaults] synchronize];

將第一個NSDictionary添加到NSUserDefaults很容易。 但是,很難掌握NSDictionary值並收集新的值機值。 例如,我第一次使用上面給出的代碼塊將這些值添加到NSUserDefaults中。

{
CheckinID = 1;
Date = "2016.09.19 21:15";
Latitude = "37.33233141";
Longitute = "-122.03121860";
Note = "test";
ProjectID = "2";
TypeID = "1";
}

當我要添加其他簽到詳細信息時,我需要使用舊的簽到詳細信息並收集新的簽到詳細信息。 例如;

{
CheckinID = 1;
Date = "2016.09.19 21:15";
Latitude = "37.33233141";
Longitute = "-122.03121860";
Note = "test";
ProjectID = "2";
TypeID = "1";
},
{
CheckinID = 2;
Date = "2016.09.20 21:15";
Latitude = "35.33233141";
Longitute = "120.03121860";
Note = "test2";
ProjectID = "5";
TypeID = "4";
}

像這樣,在我需要獲取每個入住信息之后。 順便說一句,CheckinID將作為最后一個checkinID遞增1。 你能幫助我嗎? 謝謝。

您需要將字典添加到數組並將數組保存到字典中。

[myArray addObject:oldcheckin];

 NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
  [userDefaults setObject:myArray forKey:@"myDictArray"];

然后取回它,

 NSMutableArray *arrayOfDicts = [[userDefaults objectForKey:@"myDictArray"]mutableCopy];

並將新字典添加到數組

 [arrayOfDicts addObject: newcheckin];

並將新數組保存為用戶默認設置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM