显示基于uiswitch状态的数据

时间:2014-03-24 21:24:37

标签: ios objective-c

我正在尝试根据用户是否选择了一个开关来显示数据。用户可以选择一个或两个开关来打开或打开一个或另一个。然后将根据开关的状态显示数据。

我设法让它加载,但它只显示来自plist文件中的dare数组的数据,并且重要的是交换机所在的状态显示不敢为真,或两者兼而有之。

- (IBAction)shownext:(id)sender {
    if (!self.plistArray) {
        NSString *path = [[NSBundle mainBundle] pathForResource:
                          @"data" ofType:@"plist"];  
        NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
        if ([[defaults objectForKey:@"truthonoff"] isEqualToString:@"YES"] && [[defaults objectForKey:@"dareonoff"] isEqualToString:@"YES"]  ) {
            NSDictionary *plistDict1 = [[NSDictionary alloc] initWithContentsOfFile:path];
            NSArray * plistArray1 = plistDict1[@"truth"];
            NSDictionary *plistDict2 = [[NSDictionary alloc] initWithContentsOfFile:path];
            NSArray *plistArray2 = plistDict2[@"dare"];
            self.plistArray = [[plistArray1 arrayByAddingObjectsFromArray:plistArray2] mutableCopy];

        } else if ([[defaults objectForKey:@"truthonoff"] isEqualToString:@"YES"] ) {
            NSDictionary *plistDict3 = [[NSDictionary alloc] initWithContentsOfFile:path];
            NSArray *plistArray3 = plistDict3[@"truth"] ;
            self.plistArray = [plistArray3 mutableCopy];
            NSLog(@"%@", plistArray);
        } else ([[defaults objectForKey:@"dareonoff"] isEqualToString:@"YES"] ); {
            NSDictionary *plistDict4 = [[NSDictionary alloc] initWithContentsOfFile:path];
            NSMutableArray *plistArray4 = plistDict4[@"dare"];
            self.plistArray = [plistArray4 mutableCopy];
            NSLog(@"%@", plistArray);
        }
    }
}



 -(void)stateSwitched:(id)sender {
    UISwitch *tswitch = (UISwitch *)sender;
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    [defaults setObject: tswitch.isOn ? @"YES" : @"NO" forKey:@"truthonoff"];

    [defaults synchronize];
}

-(void)stateSwitcheddare:(id)sender {
    UISwitch *tswitch = (UISwitch *)sender;
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    [defaults setObject: tswitch.isOn ? @"YES" : @"NO" forKey:@"dareonoff"];

    [defaults synchronize];
}

这是我设置对象的代码

1 个答案:

答案 0 :(得分:3)

尝试使用boolForKey而不是objectForKey。而另一方面,为什么其他人有条件?:

if ([defaults boolForKey:@"truthonoff"] && [defaults boolForKey:@"dareonoff"]) {
     // Both true 
} else if ([defaults boolForKey:@"truthonoff"] && ![defaults boolForKey:@"dareonoff"]) {
     // truthonoff true, dareonoff false
} else if (![defaults boolForKey:@"truthonoff"] && [defaults boolForKey:@"dareonoff"]) {
     // truthonoff false, dareonoff true
} else {
     // Both false
} 

确保在NSUserStandardDefaults中存储布尔值时做两件事:

  1. 使用setBool setter:[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@" a_key"];
  2. 请记住同步standardUserDefaults以保存值。