数据持久化(一)-----归档 读写 文件路径

<pre>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]autorelease];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];

/*HMTRootViewController * rootVC = [[HMTRootViewController alloc]init];
self.window.rootViewController = rootVC;
[rootVC release];*/

// 1.获取沙盒文件的主路径
NSLog(@"home = %@",NSHomeDirectory());

// 2.获取Documents的路径(获取Library的路径类似)
NSLog(@"documents = %@", [NSHomeDirectory() stringByAppendingString:@"/Documents"]);
NSLog(@"documents = %@", [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]);
NSLog(@"documents = %@",[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]);

// 3.获取tmp的路径(单独的方法,与众不同)
NSLog(@"tmp = %@",NSTemporaryDirectory());

// 4.应用程序包.app-----只有读取的权利,没有修改的权利
NSLog(@".app = %@",[[NSBundle mainBundle] bundlePath]);
NSLog(@"resource = %@",[[NSBundle mainBundle]resourcePath]);
NSLog(@".exec = %@",[[NSBundle mainBundle] executablePath]);

//[self simpleOperationOfApp];
[self complexOperationOfApp];
[self complexArrayOperationOfApp];

return YES;

}

pragma mark - 简单的数据文件write/read

  • (void)simpleOperationOfApp{

pragma mark 字符串---txt

// 1.获取存储文件的上一级路径
NSString * documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

// 2.拼接一个完整的文件存储路径
NSString * filePath = [documentsPath stringByAppendingPathComponent:@"text.txt"];

// 3.write数据
NSString * saveString = @"我叫胡明涛";
[saveString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];

// 4.从文件中read
NSString * readString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
NSLog(@"%@",readString);

pragma mark 数组---plist

NSString * cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString * arrayFilePath = [cachesPath stringByAppendingPathComponent:@"names.plist"];
NSArray * writeArray = @[@"吴凯",@"许珍珍",@"左友东"];
[writeArray writeToFile:arrayFilePath atomically:YES];

NSArray * readArray = [NSArray arrayWithContentsOfFile:arrayFilePath];
NSLog(@"%@",readArray);

pragma mark 字典---plist

NSString * tmpPath = NSTemporaryDirectory();
NSString * dicFilePath = [tmpPath stringByAppendingPathComponent:@"dic.plist"];
NSDictionary * writeDic = @{@"name": @"HMT",@"sex":@"female"};
[writeDic writeToFile:dicFilePath atomically:YES];

NSDictionary * readDic = [NSDictionary dictionaryWithContentsOfFile:dicFilePath];
NSLog(@"%@",readDic);

// 修改数据
[readDic setValue:@"humingtao" forKey:@"name"];
[readDic writeToFile:dicFilePath atomically:YES];
NSLog(@"%@",readDic);

pragma mark NSData

// 获取图片对象
UIImage * writeImage = [UIImage imageNamed:@"OJ2NMBNXQ1G5_20121120051201760"];

// 图片对象转变为NSData类型
NSData * writeData = UIImagePNGRepresentation(writeImage);

NSString * imageFilePath = [documentsPath stringByAppendingPathComponent:@"美女.png"];
[writeData writeToFile:imageFilePath atomically:YES];

NSData * readData = [NSData dataWithContentsOfFile:imageFilePath];
// imageNamed------图片会存入缓存,下次加载很迅速,但是耗内存,图片一大就嗝屁了
UIImage * readImage = [UIImage imageWithData:readData];
// 从文件路径中找,调用一次就重新加载一次,只是显示图片,不加载到内存(后缀名不要加".")
[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"美女" ofType:@"png"]];
NSLog(@"%@",readImage);
NSLog(@"%@",[UIImage imageWithContentsOfFile:imageFilePath]);

}

pragma mark - 单个--复杂的数据对象write/read-------NSCoding协议

  • (void)complexOperationOfApp{

    UIButton * archiver = [UIButton buttonWithType:UIButtonTypeSystem];
    archiver.frame = CGRectMake(20, 100, 100, 40);
    [archiver setTitle:@"归档(序列化)" forState:UIControlStateNormal];
    [archiver addTarget:self action:@selector(onClickArchiverButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.window addSubview:archiver];

    UIButton * unArchiver = [UIButton buttonWithType:UIButtonTypeSystem];
    unArchiver.frame = CGRectMake(160, 100, 120, 40);
    [unArchiver setTitle:@"反归档(反序列化)" forState:UIControlStateNormal];
    [unArchiver addTarget:self action:@selector(onClickUnArchiverButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.window addSubview:unArchiver];
    }

pragma mark 对复杂的数据对象进行写入操作.原理:复杂的数据对象序列化为NSData,将NSData写入文件,实现数据持久化

  • (void)onClickArchiverButton:(UIButton *)button{

    /**

    • 1.自定义复杂的数据类型,例如ABPerson
    • (1)ABPerson必须实现NSCoding协议的方法
    • (2)ABPerson中的实例变量或属性,也必须实现NSCoding协议的方法
    • (3)ABPerson中的基本数据类型没有过多限制
    • 2.创建一个序列化工具对象
    • 3.先找路径
    • 4.对复杂的数据类型对象进行序列化
    • 5.结束 finishEncoding
    • 6.NSData写入
      */
      HMTABPerson * person = [[HMTABPerson alloc]init];
      person.name = @"HMT";
      person.age = 25;

    NSMutableData * archiverData = [NSMutableData data];
    NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:archiverData];

    [archiver encodeObject:person forKey:@"PersonKey"];

    [archiver finishEncoding];

    NSString * documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSString * filePath = [documents stringByAppendingPathComponent:@"person.data"];

    [archiverData writeToFile:filePath atomically:YES];

    [person release];
    [archiver release];

}

pragma mark 从文件中读取数据来实例化复杂对象数据操作

  • (void)onClickUnArchiverButton:(UIButton *)button{

    /**

    • 1.先找路径
    • 2.NSData读出
    • 3.创建一个反序列化工具
    • 4.反序列化
    • 5.结束 finishDecoding
    • 6.操作对象了
      */
      NSString * documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
      NSString * filePath = [documents stringByAppendingPathComponent:@"person.data"];

    NSData * unarchiverData = [NSData dataWithContentsOfFile:filePath];

    NSKeyedUnarchiver * unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:unarchiverData];

    HMTABPerson * person = [unarchiver decodeObjectForKey:@"PersonKey"];

    [unarchiver finishDecoding];

    NSLog(@"%@",person.name);

    [unarchiver release];

}

pragma mark - 数组--复杂的数据对象write/read-------NSCoding协议

  • (void)complexArrayOperationOfApp{

    UIButton * archiver = [UIButton buttonWithType:UIButtonTypeSystem];
    archiver.frame = CGRectMake(20, 200, 100, 40);
    [archiver setTitle:@"归档(序列化)" forState:UIControlStateNormal];
    [archiver addTarget:self action:@selector(onClickArchiverArrayButton) forControlEvents:UIControlEventTouchUpInside];
    [self.window addSubview:archiver];

    UIButton * unArchiver = [UIButton buttonWithType:UIButtonTypeSystem];
    unArchiver.frame = CGRectMake(160, 200, 120, 40);
    [unArchiver setTitle:@"反归档(反序列化)" forState:UIControlStateNormal];
    [unArchiver addTarget:self action:@selector(onClickUnArchiverArrayButton) forControlEvents:UIControlEventTouchUpInside];
    [self.window addSubview:unArchiver];

}

pragma mark 写入

  • (void)onClickArchiverArrayButton{

    NSMutableData * archiverData = [NSMutableData data];
    NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:archiverData];

    HMTABPerson * person1 = [[HMTABPerson alloc]init];
    person1.name = @"陈凤长";
    person1.age = 24;

    HMTABPerson * person2 = [[HMTABPerson alloc]init];
    person2.name = @"胡明涛";
    person2.age = 24;

    NSArray * personArray = @[person1,person2];

    [archiver encodeObject:personArray forKey:@"PersonArrayKey"];

    [archiver finishEncoding];

    NSString * tmpPath = NSTemporaryDirectory();
    NSString * filePath = [tmpPath stringByAppendingPathComponent:@"personArray.plist"];

    [archiverData writeToFile:filePath atomically:YES];

    [person1 release];
    [person2 release];
    [archiver release];

}

pragma mark 读取

  • (void)onClickUnArchiverArrayButton{

    NSString * tmpPath = NSTemporaryDirectory();
    NSString * filePath = [tmpPath stringByAppendingPathComponent:@"personArray.plist"];

    NSData * unarchiverData = [NSData dataWithContentsOfFile:filePath];

    NSKeyedUnarchiver * unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:unarchiverData];

    NSArray * personArray = [unarchiver decodeObjectForKey:@"PersonArrayKey"];

    [unarchiver finishDecoding];

    HMTABPerson * person1 = [personArray objectAtIndex:0];
    HMTABPerson * person2 = [personArray objectAtIndex:1];

    NSLog(@"%@ %@",person1.name,person2.name);

    [unarchiver release];

}
HMTABPerson.h

import <Foundation/Foundation.h>

@interface HMTABPerson : NSObject <NSCoding>

@property (nonatomic,assign)int age;
@property (nonatomic,copy) NSString * name;

@end
HMTABPerson.m

import "HMTABPerson.h"

@implementation HMTABPerson

  • (void)dealloc{

    [_name release];
    [super dealloc];
    }

// 序列化,编码

  • (void)encodeWithCoder:(NSCoder *)aCoder{

    [aCoder encodeObject:_name forKey:@"NameKey"];
    [aCoder encodeInt:_age forKey:@"AgeKey"];

}

// 反序列化,解码

  • (id)initWithCoder:(NSCoder *)aDecoder{

    if (self = [super init]) {

      self.name = [aDecoder decodeObjectForKey:@"NameKey"];
      self.age  = [aDecoder decodeIntForKey:@"AgeKey"];
    

    }

    return self;
    }

@end</pre>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,440评论 5 467
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,814评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,427评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,710评论 1 270
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,625评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,014评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,511评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,162评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,311评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,262评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,278评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,989评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,583评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,664评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,904评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,274评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,856评论 2 339

推荐阅读更多精彩内容