您的位置:首页 > 移动开发 > IOS开发

从零开始学习iOS开发-股票记帐本1.0(2)

2015-09-25 23:05 489 查看

4. 数据持久化

定义一个NsMutable *Data来存储数据,在这个App中使用属性文件进行数据持久话。具体的数据持久化代码如下

-(id)init{
//当应用从storyboard中加在视图控制器时,uikit将会自动触发该方法
if ((self=[super init])) {
[self loadData];
}
return self;
}
#pragma mark 数据加载和保存
- (NSString *)documentsDirectory{
NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);//NSDocumentDirectory表明查找Documents目录的路径,NSUserDomainMask表明讲搜素限制在应用的沙盒内
NSString *documentsDirectory=path[0];//每个应用只有一个Documents目录
return documentsDirectory;
}

- (NSString *)dataFilePath{
//创建到plist的完整路径
return [[self documentsDirectory]stringByAppendingPathComponent:@"data.plist"];
}

- (void)saveData{
NSMutableData *data=[[NSMutableData alloc]init];
NSKeyedArchiver *archiver=[[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
[archiver encodeObject:self.Data forKey:@"data"];//_局部变量,self属性
[archiver finishEncoding];
[data writeToFile:[self dataFilePath] atomically:YES];
//获取sellData数组中的内容,然后分两步讲它转换成二进制数据块,然后写进到文件中,chapter13p5

}
- (void) loadData{
NSString *path=[self dataFilePath];
//检查沙盒中是否存在该文件
if ([[NSFileManager defaultManager]fileExistsAtPath:path]) {
//当应用从沙河中找到path.plist文件时,我们无需创建一个新的数组,可以从该文件中加载整个数组和其中内容(savechecklistitem的逆向操作)
NSData *data=[[NSData alloc]initWithContentsOfFile:path];//将文件内容加载到nsdata对象中
NSKeyedUnarchiver *unarchiver=[[NSKeyedUnarchiver alloc]initForReadingWithData:data];//创建一个nskeyedunarchiver对象
self.Data=[unarchiver decodeObjectForKey:@"data"];
[unarchiver finishDecoding];
}else{
self.Data=[[NSMutableArray alloc]initWithCapacity:100];
}
}


5. 数据的加载和保存

4中只负责数据的持久化,此外还需要对数据进行保存和加载,这个过程在stockData.h和.m文件中进行,一下罗列主要代码

.h文件

@interface stockData : NSObject<NSCoding>

@property (strong, nonatomic) NSMutableArray *sellData;


.m文件

- (id)init{
//当用户添加一个新的stockdata到应用中时会调用常规init方法
if ((self=[super init])) {
self.sellData=[[NSMutableArray alloc]initWithCapacity:20];
}
return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder{
//加载
if ((self=[super init])) {
self.sellData=[aDecoder decodeObjectForKey:@"SellData"];
}
return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder{
//保存
[aCoder encodeObject:self.sellData forKey:@"SellData"];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios开发 存储