简体   繁体   中英

NSUserDefaults with UISegmentedControl

I have three UISegmented controls (In a utility application), each of which store their selected segments in UserDefaults when the values is changed. When the settings pane is loaded (the side with the three segmented controls), I access NSUserDefaults to highlight the current settings. For whatever reason, two of them work perfectly as desired, but one seems to randomly fluctuate when the user moves from settings pane to the mainview and back to the settings pane......

This is used to set the selected segment on flip to settings pane:

int setting2 = [defaults integerForKey:SegmentKey];
if(setting2 == 0)
{ NSLog(@"selected 0"); segmentedControlC.selectedSegmentIndex = 0; }
else
{ NSLog(@"selected 1"); segmentedControlC.selectedSegmentIndex = 1; }

This is used to assign a value to the key "SegmentKey" when the user makes a change to the selectedSegmentIndex

[defaults setInteger:segmentedControlC.selectedSegmentIndex forKey:SegmentKey];

Yet, for some reason, when I (in the simulator) press the "0" index, flip back to the main view, then return, segment one is highlighted....

Make sure that you use a unique key dor each integer in NSUserDefaults. And be sure that you synchronize NSUserDefaults after you set the integer. Also this is faster for loading your keys:

segmentedControlC.selectedSegmentIndex = [defaults integerForKey:key];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM