我必须在第一个视图控制器上随时随地隐藏它,当应用程序启动时,你有两个按钮白色和黑色。当用户按下任一按钮并向后按以查看1时,它会显示白色方块和黑色方块,具体取决于用户选择的位置。
以下代码:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidAppear:(BOOL)animated {
NSUserDefaults *SetBlack = [NSUserDefaults standardUserDefaults];
blacksquare.hidden = [SetBlack boolForKey:@"black"];
NSUserDefaults *SetWhite = [NSUserDefaults standardUserDefaults];
whitesquare.hidden = [SetWhite boolForKey:@"white"];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
和
#import "SecondViewController.h"
@interface SecondViewController ()
@end
@implementation SecondViewController
- (IBAction)black:(id)sender{
NSUserDefaults *SetBlack = [NSUserDefaults standardUserDefaults];
[SetBlack setBool:NO forKey:@"black"];
}
- (IBAction)white:(id)sender{
NSUserDefaults *SetWhite = [NSUserDefaults standardUserDefaults];
[SetWhite setBool:NO forKey:@"black"];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
答案 0 :(得分:1)
- (IBAction)black:(id)sender{
NSUserDefaults *SetBlack = [NSUserDefaults standardUserDefaults];
[SetBlack setBool:NO forKey:@"black"];
}
- (IBAction)white:(id)sender{
NSUserDefaults *SetWhite = [NSUserDefaults standardUserDefaults];
[SetWhite setBool:NO forKey:@"black"];
}
上面的代码应该是这样的
- (IBAction)black:(id)sender{
NSUserDefaults *SetBlack = [NSUserDefaults standardUserDefaults];
[SetBlack setBool:NO forKey:@"black"];
[SetBlack synchronize]; // added synchronize method
}
- (IBAction)white:(id)sender{
NSUserDefaults *SetWhite = [NSUserDefaults standardUserDefaults];
[SetWhite setBool:NO forKey:@"black"];
[SetWhite synchronize]; // added synchronize method
}
的文档
因为此方法是定期自动调用的,所以只有在您不能等待自动同步时(例如,如果您的应用程序即将退出)或者您希望将用户默认值更新为打开时,才使用此方法即使您没有进行任何更改,也可以使用磁盘。
答案 1 :(得分:0)
您必须使用[[NSUserDefaults standardDefaults] synchronize];在NSUserDefaults中设置值以保存。