iOS开发 使用NSUserDefaults 保存数据

NSUserDefaults类似android中的SharedPreferences,可以把数据持久化到设备中。


//
//  ViewController.h
//  Data
//
//  Created by 方 海鹏 on 12-10-28.
//  Copyright (c) 2012年 方 海鹏. All rights reserved.
//

#import 

@interface ViewController : UIViewController
@property (strong, nonatomic) IBOutlet UILabel *label;
@property (strong,nonatomic) NSUserDefaults *userDefaults;
- (IBAction)read:(id)sender;
- (IBAction)write:(id)sender;

@end


//
//  ViewController.m
//  Data
//
//  Created by 方 海鹏 on 12-10-28.
//  Copyright (c) 2012年 方 海鹏. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    _userDefaults=[NSUserDefaults standardUserDefaults];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    _userDefaults=nil;
}
/*
 读
 */
- (IBAction)read:(id)sender {
    
    NSString *string=[_userDefaults valueForKey:@"string"];
    _label.text=string;
    
    
}
/*
 写
 */
- (IBAction)write:(id)sender {
    [_userDefaults setObject:@"保存" forKey:@"string"];
    [_userDefaults synchronize];
}
@end

© 2012, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记