2012-02-04 125 views
1

我一直在嘗試將天數保存在我的tableViewController行中的UISwitch狀態無濟於事。我已經看過各種stackoverflow問題和響應和蘋果文檔,但似乎沒有任何工作在我的應用程序。保存UISwitch結果和NSUserDefaults

這裏是我的應用程序的委託:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; 

    NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:@"No" forKey:@"emailSwitch"]; 

    [defaults registerDefaults:appDefaults]; 

    [defaults synchronize]; 
} 

我有Root.plist在Settings.bundle集,這似乎是工作和保存在應用設置開關的結果,但不是在tableViewController 。例如,如果我在設置中將其切換爲「打開」,當我將一個對象添加到我的tableViewController時,開關會「關閉」。

這裏是在tableViewController.h文件相關代碼:

@property (nonatomic, getter=isOn) BOOL on; 

- (void)toggleValue:(id)sender; 

這裏是在tableViewController M檔相關代碼:

- (void)viewWillAppear:(BOOL)animated 
{  
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"emailSwitch"]) 
    { 
     [emailSwitch setOn:YES animated:NO]; 
    } 
    else 
    { 
     [emailSwitch setOn:NO animated:NO]; 
    } 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 

    customTableViewCell *cell = (customTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell == nil) { 

     cell = [[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 

    } 

//Code regarding cell contents here 

    UISwitch *switchObj = [[UISwitch alloc] initWithFrame:CGRectZero]; 

    [switchObj addTarget:self action:@selector(toggleValue:) forControlEvents:(UIControlEventValueChanged | UIControlEventTouchDragInside)]; 

    cell.accessoryView = switchObj; 

    return cell; 
} 

-(void)toggleValue:(id)sender 
{ 
    [[NSUserDefaults standardUserDefaults] setBool:emailSwitch.on forKey:@"emailSwitch"]; 

    [[NSUserDefaults standardUserDefaults] synchronize]; 
} 

當你的對象添加到tableViewController和將UISwitch切換爲「on」,它不會保存「on」狀態。我嘗試了各種方法,但沒有任何工作。如果有人能告訴我我做錯了什麼,我會很感激。預先感謝您提供的任何幫助。

回答

2

如果我正確理解你的問題,你的toggleValue方法應該是這樣的:

-(void)toggleValue:(UISwitch*)sw 
{ 
    [[NSUserDefaults standardUserDefaults] setBool:sw.on forKey:@"emailSwitch"]; 

    [[NSUserDefaults standardUserDefaults] synchronize]; 
} 
+0

謝謝回答的問題,但你可以看到有人問10個月之前 - 我決定放棄什麼WASN」工作並重新開始。 – PopUp 2013-02-05 23:38:29