我有一个 UISwitch,它在 CoreData 中将 BOOL 设置为 1 或 0。但是,当用户使用 Switch 加载视图时,核心数据会识别出 Switch 设置为 1(打开)但仍显示关闭。这是下面的代码。注意:当您进入和退出应用程序时,开关会正确显示,但如果您关闭手机,或者停止并启动iPhone模拟器,它会显示。有人可以帮忙吗?
“setSwtich”是 UISwitch 上的方法,“list”是 UISwitch 的名称,“indicator”是存储 BOOL 的核心数据事件属性。
-(IBAction)setSwitch
{
if (list.on)
{
[event setIndicator:[NSNumber numberWithInt:1]];
NSError *error;
if (![managedObjectContext save:&error])
{
NSLog(@"there was an error in Save");
}
}
else [event setIndicator:[NSNumber numberWithInt:0]];
NSError *error;
if (![managedObjectContext save:&error])
{
NSLog(@"there was an error in Save");
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
if (event.indicator == [NSNumber numberWithInt:1]) {
[list setOn:YES animated:NO];
}
else nil;
}
-(void)viewDidAppear:(BOOL)animated
{
if (event.indicator == [NSNumber numberWithInt:1]) {
[list setOn:YES animated:NO];
}
}
- (void)viewDidUnload
{
if (list.on) {
[event setIndicator:[NSNumber numberWithInt:1]];
}
NSError *error;
if (![managedObjectContext save:&error])
{
NSLog(@"there was an error in Save");
}
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
-(void)viewDidDisappear:(BOOL)animated
{
if (list.on) {
[event setIndicator:[NSNumber numberWithInt:1]];
}
NSError *error;
if (![managedObjectContext save:&error])
{
NSLog(@"there was an error in Save");
}
}