数据存储学习

来源:互联网 发布:金融大数据分析师待遇 编辑:程序博客网 时间:2024/05/24 05:09

使用文件持久化

- (NSString*)filePath{    NSArray *documentDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);    NSString *doc =  [documentDir objectAtIndex:0];    return [doc stringByAppendingPathComponent:@"file.txt"];}- (IBAction)saveData:(id)sender{    NSString *fPath = [self filePath];    NSString *content = _textField.text;    NSError *error;    BOOL rs = [content writeToFile:fPath atomically:YES encoding:NSUnicodeStringEncoding error:&error];    if (!rs) {        NSLog(@"file:%@,\nerror:%@",fPath,error);    }}- (IBAction)loadData:(id)sender{    NSString *fPath = [self filePath];    NSError *error;    NSString *content = [NSString stringWithContentsOfFile:fPath encoding:NSUnicodeStringEncoding error:&error];    if (error) {        NSLog(@"file:%@,\nerror:%@",fPath,error);    }    _textView.text = content;}



nsuserdefault持久化

- (void)viewDidLoad{    [super viewDidLoad];    // Do any additional setup after loading the view from its nib.    [self updateData];    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveData) name:UIApplicationDidEnterBackgroundNotification object:nil];}- (void)saveData{    [[NSUserDefaults standardUserDefaults]setObject:_textField.text forKey:@"data"];    [[NSUserDefaults standardUserDefaults] synchronize];}- (void)updateData{    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];    _textField.text = [ud valueForKey:@"data"];}




0 0
原创粉丝点击