iOS 数据持久性存储-属性列表

iOS上常用四种数据存取方法有:

  1.属性列表

  2.对象归档

  3.iOS的嵌入式关系数据库(SQLite3)

  4.苹果公司提供持久性共聚Core Data

  由于苹果公司的沙盒机制,每个应用程序都有自己的/Documents文件夹,各自的应用程序只能读写自己的/Documents目录内容

  这里将对以上4个内容分开解释。

  属性列表:

  这里你可以新建一个项目Persistence来熟悉属性列表

  1.放置4个UILabel和4个UITextField到界面上(小技巧:放好第一行label和textfield后,按住option键,往下拖拽,就可复制)

  

  2.为每个UITextField在XXViewController.h里定义输出口IBoutlet

    可以在窗口右上角打开助理编辑器,按住control键,依次从UITextField拖到Persistence.h里,如图

  

  3.在XXViewController.h建立两个方法,一个用于返回数据文件完整路径名,一个用于在程序被调到后台时开始保存UITextField内容

  XXViewController.h完整代码如下:

  

#import <UIKit/UIKit.h>

@interface BSLViewController : UIViewController
@property (weak, nonatomic) IBOutlet UITextField *field1;
@property (weak, nonatomic) IBOutlet UITextField *field2;
@property (weak, nonatomic) IBOutlet UITextField *field3;
@property (weak, nonatomic) IBOutlet UITextField *field4;


- (NSString *)dataFilePath;
- (void)applicationWillResignActive:(NSNotification *)notification;
@end
View Code

 

  4.在XXViewController.m实现方法.

  在#import下方定义一个宏文件名#define kFilename @"myData.plist"

  在@implementation下方同步.h中声明的属性@synthesize field1,field2,field3,field4;

  

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    NSString *filePath = [self dataFilePath];
    //检查数据文件是否存在,如果存在就用此文件内容实例化数组
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
        field1.text = [array objectAtIndex:0];
        field2.text = [array objectAtIndex:1];
        field3.text = [array objectAtIndex:2];
        field4.text = [array objectAtIndex:3];
    }
    
    //注册一个通知,程序进入后台立即执行applicationWillResignActive:方法
    UIApplication *app = [UIApplication sharedApplication];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app];
}
View Code
 //用于返回数据文件完整路径名
- (NSString *)dataFilePath{
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//数组索引0处就是Documentd目录
    NSString *documentsDirectory = [path objectAtIndex:0];
    return [documentsDirectory stringByAppendingPathComponent:kFilename];
}
View Code
    //当用户不再与程序交互,调用此方法
- (void)applicationWillResignActive:(NSNotification *)notification{
    NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
    [mutableArray addObject:field1.text];
    [mutableArray addObject:field2.text];
    [mutableArray addObject:field3.text];
    [mutableArray addObject:field4.text];
    //将内容写入到属性列表中
    [mutableArray writeToFile:[self dataFilePath] atomically:YES];
}
View Code

 

posted @ 2014-07-06 22:58  一码一生  阅读(217)  评论(0编辑  收藏  举报