iOS Storing the UISegmentedControl selection in NSUserDefaults

iphone, nsuserdefaults, uisegmentedcontrol

Solution

You'd simply use the selectedSegmentIndex: method of the UISegmentedControl and then use the setInteger:forKey: method within NSUserDefaults. The reason for this (as you seem to be hinting at in your question) is that the selectedSegmentIndex method returns an NSInteger. (Its full method signature is: `@property(nonatomic) NSInteger selectedSegmentIndex`)

When you reload your app, you'd then set the corresponding segment to active (once again via selectedSegmentIndex).

However, unless you're setting a default (via Interface Builder, or programatically), you should check the returned selectedSegmentIndex integer against the UISegmentedControlNoSegment constant to make sure you're not attempting to store what is effectively "no selection".

Problem

Is there some way to store a UISegmentedControl value into NSUserDefaults? Should I use it like the integer value in NSUserDefaults?

Original source