如何使用nsuserdefaults和.hidden保存和加载图片到另一个视图控制器上



我必须在第一个视图控制器上设置正方形,它在任何时候都是隐藏的,当应用程序启动时,你有两个白色和黑色按钮。当用户按下任意一个按钮并按下返回到视图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
- (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
}

来自NSUserDefaults synchronize的文档

因为这个方法是定期自动调用的,所以只有当你不能等待自动同步时(例如,如果你的应用程序即将退出),或者如果你想更新用户默认值到磁盘上,即使你没有做任何改变,也要使用这个方法。

你必须使用[[NSUserDefaults standardDefaults] synchronize];

最新更新