0

我一直在尝试UISwitch在我的文件中保存多个开关的状态,grocery.m因此当用户终止应用程序时,开关的状态将保持原样。到目前为止,我就是这样做的,但没有任何运气。我认为这个问题必须在我的grocery.m文件中而不是appDelegate.m. 如果有人能告诉我我的错误在哪里,将不胜感激。谢谢!

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 


NSUserDefaults* defaults  = [NSUserDefaults standardUserDefaults];    

push.switchstore1.on = [defaults boolForKey: @"mySwitch1"];
push.switchstore2.on = [defaults boolForKey: @"mySwitch2"];
push.switchstore3.on = [defaults boolForKey: @"mySwitch3"];

UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:UIApplicationWillTerminateNotification object:app]; //Listener
    }

 - (void)applicationWillTerminate:(UIApplication *)application {



NSUserDefaults* defaults  = [NSUserDefaults standardUserDefaults];
[defaults setBool: push.store1.on forKey: @"mySwitch1"];
[defaults setBool: push.store2.on forKey: @"mySwitch2"];
[defaults setBool: push.store3.on forKey: @"mySwitch3"];

[[NSUserDefaults standardUserDefaults] synchronize];
[self saveContext]; //Already in the method by default
}

杂货店.M 内

  -(void) viewDidLoad
 { 
 NSUserDefaults* defaults  = [NSUserDefaults standardUserDefaults];
 switchStore1.on = [defaults boolForKey: @"mySwitch1"];
 switchStore2.on = [defaults boolForKey: @"mySwitch2"];
 switchStore3.on = [defaults boolForKey: @"mySwitch3"];
 }

编辑已添加到 delegate.h 的内容(属性也已在 .m 中合成)

groceryViewController *push;
@property (nonatomic, retain) groceryViewController *push;
4

2 回答 2

0

在您的应用程序WillTerminate 中,您将启动一个全新的groceryViewController,它将始终具有开关的默认“关闭”值。您需要使用在应用程序的 didFinishLaunchingWithOptions 中实例化的相同的groceryViewController。有多种方法可以做到这一点,包括使用全局变量或使用 AppDelegate 中的属性。

于 2012-05-21T03:44:39.697 回答
0

您总是在创建 的新实例groceryViewController,因此它不会引用您要从中捕获信息的相同内存位置。

于 2012-05-21T03:47:00.550 回答