Not all NSUserDefaults are restored on app relaunc

2019-09-14 18:17发布

问题:

I am converting 2 custom lists into a json string and storing it the NSUserDefaults. Something like so:-

NSUserDefaults.StandardUserDefaults.SetString(JsonConvert.SerializeObject(stationList.Take(50)), "StationList1");
NSUserDefaults.StandardUserDefaults.SetString(JsonConvert.SerializeObject(stationList.Skip(50).Take(50)), "StationList2");  

If I try and retrieve them immediately after saving them like below I get the saved values:-

savedStationList1 = NSUserDefaults.StandardUserDefaults.StringForKey("StationList1");
  savedStationList2 = NSUserDefaults.StandardUserDefaults.StringForKey("StationList2");  

But the issue is if I restart the app, and try to get the above values in another part of the code, I only get the value for:-

savedStationList2 = NSUserDefaults.StandardUserDefaults.StringForKey("StationList2");  

and the value for below is always null :-

 savedStationList1 = NSUserDefaults.StandardUserDefaults.StringForKey("StationList1");

I do not override these values anywhere within the app. Is there a way I can solve this?

Any help is appreciated

回答1:

Although natively the iOS system does store data added through 'userdefaults' it may not do this instantly. I would suggest adding the following line:

NSUserDefaults.StandardUserDefaults.Synchronise();

After you store data to standard user defaults run the synchronise and test that you can extract the data, you should find that this will now work correctly for you.