标签:
#import "ViewController.h" @interface ViewController () @property (weak, nonatomic) IBOutlet UITextField *nameTextField; @property (weak, nonatomic) IBOutlet UITextField *ageTextField; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; //1.测试部分:获取沙盒的Library目录 NSArray *libraryPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); NSString *libraryPath = [libraryPaths lastObject]; NSLog(@"libraryPath:%@",libraryPath); //2.初始化数据(从第四步保存的数据,读取它,并显示) [self initDataByUserDefault]; //3.在用户将后台程序移除后,需要知道针对这个动作的触发时间/方法(通知) [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:[UIApplication sharedApplication]]; //4.在后面 } - (void)initDataByUserDefault{ //获取全局的NSUserDefaults对象 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; //使用defaults对象来获取保存的数据 NSString *nameStr = [defaults objectForKey:@"name"]; NSString *ageStr = [defaults objectForKey:@"age"]; //将上步获取的数据,赋值给nameTextField if (nameStr) { self.nameTextField.text = nameStr; } if (ageStr) { self.ageTextField.text = ageStr; } } - (void)applicationWillDidEnterBackground:(NSNotification *)notitication{ NSLog(@"测试:进入后台时机"); //4.在触发方法中去保存你要保存的数据。 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; [defaults setObject:self.nameTextField.text forKey:@"name"]; [defaults setObject:self.ageTextField.text forKey:@"age"]; //强制将用户输入的名字和年龄数据保存到硬盘中 //这里不是自己决定的,由系统决定 ,存在Library目录下。 [defaults synchronize]; } @end
标签:
原文地址:http://www.cnblogs.com/endtel/p/4828882.html