在NSUserDefaults中存储UISegmentedControl选择。

时间:2022-10-17 21:44:46

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

是否有办法将UISegmentedControl值存储到NSUserDefaults中?我应该像使用NSUserDefaults的整数值一样使用它吗?

1 个解决方案

#1


5  

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)

您只需使用UISegmentedControl的selectedSegmentIndex:方法,然后在NSUserDefaults中使用setInteger:forKey:方法。这样做的原因(正如您在问题中所暗示的)是selectedSegmentIndex方法返回一个NSInteger。(其完整的方法签名是:@property(非原子)NSInteger selectedSegmentIndex)

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

当您重新加载应用程序时,您将相应的段设置为active(再次通过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".

但是,除非您设置了默认值(通过接口构建器或编程方式),您应该检查返回的selectedSegmentIndex整数,以确保您不会尝试存储有效的“no selection”。

#1


5  

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)

您只需使用UISegmentedControl的selectedSegmentIndex:方法,然后在NSUserDefaults中使用setInteger:forKey:方法。这样做的原因(正如您在问题中所暗示的)是selectedSegmentIndex方法返回一个NSInteger。(其完整的方法签名是:@property(非原子)NSInteger selectedSegmentIndex)

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

当您重新加载应用程序时,您将相应的段设置为active(再次通过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".

但是,除非您设置了默认值(通过接口构建器或编程方式),您应该检查返回的selectedSegmentIndex整数,以确保您不会尝试存储有效的“no selection”。