【问题标题】:how to save switch state with user defaults?如何使用用户默认值保存开关状态?
【发布时间】:2011-04-04 21:22:06
【问题描述】:

有没有一种方法可以用 NSUserDefaults 存储 UISwitch 的状态?
如果状态为 ON,我想设置一些操作...

我可以这样做吗?
谢谢!

【问题讨论】:

    标签: iphone save state nsuserdefaults uiswitch


    【解决方案1】:

    hotpaw2的答案很好,对于大分段控制(多于2个状态)也能很好的工作。但是如果你只想存储 2 个状态,为什么不直接使用 [setBool:forKey:] 这样

        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
       [userDefaults setBool:switchState forKey:@"mySwitchValueKey"];
    

    然后拿出来:

       BOOL swichState = [userDefaults boolForKey:@"mySwitchValueKey"];
    

    which imo,要简单得多,根本没有 if else 代码,没有字符串转换回和 for

    【讨论】:

    • 我相信这就是我要找的...我会尝试...谢谢!
    【解决方案2】:

    保存:

    - (void)mySwitchAction:(id)sender
    {
      if (sender == mySwitch) {
        BOOL mySwitchValue = [ sender isOn ];
        NSString *tmpString = mySwitchValue ? @"1" : @"-1" ;
        NSUserDefaults  *myNSUD = [NSUserDefaults standardUserDefaults];
        [ myNSUD setObject:tmpString forKey: @"mySwitchValueKey" ];
        [ myNSUD synchronize ];
        // do other stuff/actions
      }
    }
    

    从保存状态初始化:

    NSUserDefaults  *myNSUD = [NSUserDefaults standardUserDefaults];
    NSString *tmpString =  [ myNSUD stringForKey: @"mySwitchValueKey"];
    BOOL mySwitchValue = NO;  // or DEFAULT_VALUE
    if (tmpString != nil) { 
      mySwitchValue = ( [ tmpString intValue ] == 1 ); 
    }
    [mySwitch setOn: mySwitchValue];
    

    【讨论】:

    • 我可以使用没有声明的方法吗?我必须将状态保存在控制器中,并在验证状态并在另一个控制器中执行某些操作后...我该怎么做?
    • 这听起来像是一个新的和不同的问题。
    • @Matthew:我认为这很容易,您可以在另一个视图控制器中从 userDefaults 中获取状态。查看我的答案以获得更简单的答案,根本没有方法声明:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-08
    • 1970-01-01
    相关资源
    最近更新 更多