蓝懿ios技术交流和心得分享16.1.16

来源:互联网 发布:淘宝找不到菜鸟驿站 编辑:程序博客网 时间:2024/04/29 18:43

iOS开发UI篇—ios应用数据存储方式(归档) 

一、简单说明

在使用plist进行数据存储和读取,只适用于系统自带的一些常用类型才能用,且必须先获取路径相对麻烦;

偏好设置(将所有的东西都保存在同一个文件夹下面,且主要用于存储应用的设置信息)

归档:因为前两者都有一个致命的缺陷,只能存储常用的类型。归档可以实现把自定义的对象存放在文件中。

二、代码示例

1.文件结构

 

2.代码示例

 YYViewController.m文件

 1 // 2 //  YYViewController.m 3 //  02-归档 4 // 5 //  Created by apple on 14-6-7. 6 //  Copyright (c) 2014年 itcase. All rights reserved. 7 // 8  9 #import "YYViewController.h"10 #import "YYPerson.h"11 12 @interface YYViewController ()13 - (IBAction)saveBtnOnclick:(id)sender;14 - (IBAction)readBtnOnclick:(id)sender;15 16 @end17 18 @implementation YYViewController19 20 - (void)viewDidLoad21 {22     [super viewDidLoad];23 }24 25 26 - (IBAction)saveBtnOnclick:(id)sender {27     //1.创建对象28     YYPerson *p=[[YYPerson alloc]init];29     p.name=@"文顶顶";30     p.age=23;31     p.height=1.7;32     33     //2.获取文件路径34     NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];35     NSString *path=[docPath stringByAppendingPathComponent:@"person.yangyang"];36     NSLog(@"path=%@",path);37     38     //3.将自定义的对象保存到文件中39     [NSKeyedArchiver archiveRootObject:p toFile:path];40     41 }42 43 - (IBAction)readBtnOnclick:(id)sender {44     //1.获取文件路径45     NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];46     NSString *path=[docPath stringByAppendingPathComponent:@"person.yangyang"];47     NSLog(@"path=%@",path);48     49     //2.从文件中读取对象50     YYPerson *p=[NSKeyedUnarchiver unarchiveObjectWithFile:path];51     NSLog(@"%@,%d,%.1f",p.name,p.age,p.height);52 }53 @end

新建一个person类

YYPerson.h文件

 1 // 2 //  YYPerson.h 3 //  02-归档 4 // 5 //  Created by apple on 14-6-7. 6 //  Copyright (c) 2014年 itcase. All rights reserved. 7 // 8  9 #import 10 11 // 如果想将一个自定义对象保存到文件中必须实现NSCoding协议12 @interface YYPerson : NSObject13 14 //姓名15 @property(nonatomic,copy)NSString *name;16 //年龄17 @property(nonatomic,assign)int age;18 //身高19 @property(nonatomic,assign)double height;20 @end

YYPerson.m文件

 1 // 2 //  YYPerson.m 3 //  02-归档 4 // 5 //  Created by apple on 14-6-7. 6 //  Copyright (c) 2014年 itcase. All rights reserved. 7 // 8  9 #import "YYPerson.h"10 11 @implementation YYPerson12 13 // 当将一个自定义对象保存到文件的时候就会调用该方法14 // 在该方法中说明如何存储自定义对象的属性15 // 也就说在该方法中说清楚存储自定义对象的哪些属性16 -(void)encodeWithCoder:(NSCoder *)aCoder17 {18     NSLog(@"调用了encodeWithCoder:方法");19     [aCoder encodeObject:self.name forKey:@"name"];20     [aCoder encodeInteger:self.age forKey:@"age"];21     [aCoder encodeDouble:self.height forKey:@"height"];22 }23 24 // 当从文件中读取一个对象的时候就会调用该方法25 // 在该方法中说明如何读取保存在文件中的对象26 // 也就是说在该方法中说清楚怎么读取文件中的对象27 -(id)initWithCoder:(NSCoder *)aDecoder28 {29     NSLog(@"调用了initWithCoder:方法");30     //注意:在构造方法中需要先初始化父类的方法31     if (self=[super init]) {32         self.name=[aDecoder decodeObjectForKey:@"name"];33         self.age=[aDecoder decodeIntegerForKey:@"age"];34         self.height=[aDecoder decodeDoubleForKey:@"height"];35     }36     return self;37 }38 @end

3.打印效果和两个重要的错误提示

点击保存按钮和读取按钮,成功打印结果如下:

关于不实现两个协议方法的错误提示:

-(void)encodeWithCoder:(NSCoder *)aCoder方法:

    

-(id)initWithCoder:(NSCoder *)aDecoder方法:

 

三、继承类中的使用

新建一个学生类,让这个类继承自Preson这个类,增加一个体重的属性。

YYstudent.h文件

 1 // 2 //  YYstudent.h 3 //  02-归档 4 // 5 //  Created by apple on 14-6-7. 6 //  Copyright (c) 2014年 itcase. All rights reserved. 7 // 8  9 #import "YYPerson.h"10 11 @interface YYstudent : YYPerson12 //增加一个体重属性13 @property(nonatomic,assign) double weight;14 @end

YYstudent.m文件

 1 // 2 //  YYstudent.m 3 //  02-归档 4 // 5 //  Created by apple on 14-6-7. 6 //  Copyright (c) 2014年 itcase. All rights reserved. 7 // 8  9 #import "YYstudent.h"10 11 @implementation YYstudent12 13 //在子类中重写这两个方法14 - (void)encodeWithCoder:(NSCoder *)aCoder15 {16     [super encodeWithCoder:aCoder];17     NSLog(@"调用了YYStudent encodeWithCoder");18     [aCoder encodeFloat:self.weight forKey:@"weight"];19 }20 21 - (id)initWithCoder:(NSCoder *)aDecoder22 {23     if (self = [super initWithCoder:aDecoder]) {24         NSLog(@"调用了YYstudent initWithCoder");25         self.weight = [aDecoder decodeFloatForKey:@"weight"];26     }27     return self;28 }29 @end

YYViewController.m文件

 1 // 2 //  YYViewController.m 3 //  02-归档 4 // 5 //  Created by apple on 14-6-7. 6 //  Copyright (c) 2014年 itcase. All rights reserved. 7 // 8  9 #import "YYViewController.h"10 #import "YYPerson.h"11 #import "YYstudent.h"12 13 @interface YYViewController ()14 - (IBAction)saveBtnOnclick:(id)sender;15 - (IBAction)readBtnOnclick:(id)sender;16 17 @end18 19 @implementation YYViewController20 21 - (void)viewDidLoad22 {23     [super viewDidLoad];24 }25 26 27 - (IBAction)saveBtnOnclick:(id)sender {28     //1.创建对象29 //    YYPerson *p=[[YYPerson alloc]init];30 //    p.name=@"文顶顶";31 //    p.age=23;32 //    p.height=1.7;33     34     YYstudent *s=[[YYstudent alloc]init];35     s.name=@"wendingding";36     s.age=23;37     s.height=1.7;38     s.weight=62;39     //2.获取文件路径40     NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];41     NSString *path=[docPath stringByAppendingPathComponent:@"person.yangyang"];42     NSLog(@"path=%@",path);43     44     //3.将自定义的对象保存到文件中45 //    [NSKeyedArchiver archiveRootObject:p toFile:path];46      [NSKeyedArchiver archiveRootObject:s toFile:path];47     48 }49 50 - (IBAction)readBtnOnclick:(id)sender {51     //1.获取文件路径52     NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];53     NSString *path=[docPath stringByAppendingPathComponent:@"person.yangyang"];54     NSLog(@"path=%@",path);55     56     //2.从文件中读取对象57 //    YYPerson *p=[NSKeyedUnarchiver unarchiveObjectWithFile:path];58 //    NSLog(@"%@,%d,%.1f",p.name,p.age,p.height);59     YYstudent *s=[NSKeyedUnarchiver unarchiveObjectWithFile:path];60     NSLog(@"%@,%d,%.1f,%f",s.name,s.age,s.height,s.weight);61 }62 @end

点击保存按钮和读取按钮后的打印输出:

四、重要说明

1.保存数据过程:

    //1.创建对象    YYstudent *s=[[YYstudent alloc]init];    s.name=@"wendingding";    s.age=23;    s.height=1.7;    s.weight=62;        //2.获取文件路径    NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];    NSString *path=[docPath stringByAppendingPathComponent:@"person.yangyang"];    NSLog(@"path=%@",path);        //3.将自定义的对象保存到文件中     [NSKeyedArchiver archiveRootObject:s toFile:path];

2.读取数据过程:

 //1.获取文件路径    NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];    NSString *path=[docPath stringByAppendingPathComponent:@"person.yangyang"];    //2.从文件中读取对象    YYstudent *s=[NSKeyedUnarchiver unarchiveObjectWithFile:path];

3.遵守NSCoding协议,并实现该协议中的两个方法。

4.如果是继承,则子类一定要重写那两个方法。因为person的子类在存取的时候,会去子类中去找调用的方法,没找到那么它就去父类中找,所以最后保存和读取的时候新增加的属性会被忽略。需要先调用父类的方法,先初始化父类的,再初始化子类的。

5.保存数据的文件的后缀名可以随意命名。

6.通过plist保存的数据是直接显示的,不安全。通过归档方法保存的数据在文件中打开是乱码的,更安全。

实现思路:下载开始,创建一个和要下载的文件大小相同的文件(如果要下载的文件为100M,那么就在沙盒中创建一个100M的文件,然后计算每一段的下载量,开启多条线程下载各段的数据,分别写入对应的文件部分)。

项目中用到的主要类如下:

完成的实现代码如下:

主控制器中的代码:

 1 #import "YYViewController.h" 2 #import "YYFileMultiDownloader.h" 3  4 @interface YYViewController () 5 @property (nonatomic, strong) YYFileMultiDownloader *fileMultiDownloader; 6 @end 7  8 @implementation YYViewController 9 -  (YYFileMultiDownloader *)fileMultiDownloader10 {11     if (!_fileMultiDownloader) {12         _fileMultiDownloader = [[YYFileMultiDownloader alloc] init];13         // 需要下载的文件远程URL14         _fileMultiDownloader.url = @"http://192.168.1.200:8080/MJServer/resources/jre.zip";15         // 文件保存到什么地方16         NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];17         NSString *filepath = [caches stringByAppendingPathComponent:@"jre.zip"];18         _fileMultiDownloader.destPath = filepath;19     }20     return _fileMultiDownloader;21 }22 23 - (void)viewDidLoad24 {25     [super viewDidLoad];26     27 }28 29 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event30 {31     [self.fileMultiDownloader start];32 }33 34 @end

自定义一个基类

YYFileDownloader.h文件

 1 #import  2  3 @interface YYFileDownloader : NSObject 4 { 5     BOOL _downloading; 6 } 7 10 @property (nonatomic, copy) NSString *url;11 14 @property (nonatomic, copy) NSString *destPath;15 16 19 @property (nonatomic, readonly, getter = isDownloading) BOOL downloading;20 21 24 @property (nonatomic, copy) void (^progressHandler)(double progress);25 26 29 - (void)start;30 31 34 - (void)pause;35 @end

YYFileDownloader.m文件

1 #import "YYFileDownloader.h"2 3 @implementation YYFileDownloader4 @end

下载器类继承自YYFileDownloader这个类

YYFileSingDownloader.h文件

 1 #import "YYFileDownloader.h" 2  3 @interface YYFileSingleDownloader : YYFileDownloader 4  7 @property (nonatomic, assign) long long begin; 8 11 @property (nonatomic, assign) long long end; 12 @end

YYFileSingDownloader.m文件

  1 #import "YYFileSingleDownloader.h"  2 @interface YYFileSingleDownloader()   3   6 @property (nonatomic, strong) NSURLConnection *conn;  7   8  11 @property (nonatomic, strong) NSFileHandle *writeHandle; 12  15 @property (nonatomic, assign) long long currentLength; 16 @end 17  18 @implementation YYFileSingleDownloader 19  20 - (NSFileHandle *)writeHandle 21 { 22     if (!_writeHandle) { 23         _writeHandle = [NSFileHandle fileHandleForWritingAtPath:self.destPath]; 24     } 25     return _writeHandle; 26 } 27  28  31 - (void)start 32 { 33     NSURL *url = [NSURL URLWithString:self.url]; 34     // 默认就是GET请求 35     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 36     // 设置请求头信息 37     NSString *value = [NSString stringWithFormat:@"bytes=%lld-%lld", self.begin + self.currentLength, self.end]; 38     [request setValue:value forHTTPHeaderField:@"Range"]; 39     self.conn = [NSURLConnection connectionWithRequest:request delegate:self]; 40      41     _downloading = YES; 42 } 43  44  47 - (void)pause 48 { 49     [self.conn cancel]; 50     self.conn = nil; 51      52     _downloading = NO; 53 } 54  55  56 #pragma mark - NSURLConnectionDataDelegate 代理方法 57  60 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 61 { 62      63 } 64  65  68 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 69 { 70     // 移动到文件的尾部 71     [self.writeHandle seekToFileOffset:self.begin + self.currentLength]; 72     // 从当前移动的位置(文件尾部)开始写入数据 73     [self.writeHandle writeData:data]; 74      75     // 累加长度 76     self.currentLength += data.length; 77      78     // 打印下载进度 79     double progress = (double)self.currentLength / (self.end - self.begin); 80     if (self.progressHandler) { 81         self.progressHandler(progress); 82     } 83 } 84  85  88 - (void)connectionDidFinishLoading:(NSURLConnection *)connection 89 { 90     // 清空属性值 91     self.currentLength = 0; 92      93     // 关闭连接(不再输入数据到文件中) 94     [self.writeHandle closeFile]; 95     self.writeHandle = nil; 96 } 97  98 101 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error102 {103     104 }105 106 @end

设计多线程下载器(利用HMFileMultiDownloader能开启多个线程同时下载一个文件)

一个多线程下载器只下载一个文件

YYFileMultiDownloader.h文件

1 #import "YYFileDownloader.h"2 3 @interface YYFileMultiDownloader : YYFileDownloader4 5 @end

YYFileMultiDownloader.m文件

1 #import "YYFileMultiDownloader.h" 2 #import "YYFileSingleDownloader.h" 3 4 #defineYYMaxDownloadCount 4 5 6 @interface YYFileMultiDownloader() 7 @property (nonatomic, strong) NSMutableArray *singleDownloaders; 8 @property (nonatomic, assign) long longtotalLength; 9 @end10 11 @implementation YYFileMultiDownloader12 13 - (void)getFilesize14{15 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.url]];16 request.HTTPMethod = @"HEAD";17 18 NSURLResponse *response = nil;19 #warning 这里要用异步请求20 [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];21 self.totalLength =response.expectedContentLength;22 }23 24 - (NSMutableArray *)singleDownloaders25 {26 if(!_singleDownloaders) {27 _singleDownloaders = [NSMutableArray array];28 29 // 获得文件大小30 [self getFilesize];31 32 // 每条路径的下载量33 long long size = 0;34 if (self.totalLength % YYMaxDownloadCount == 0) {35 size = self.totalLength / YYMaxDownloadCount;36 } else{37 size = self.totalLength / YYMaxDownloadCount + 1;38 }39 40 // 创建N个下载器41 for (inti = 0; i) {42 YYFileSingleDownloader *singleDownloader = [[YYFileSingleDownloader alloc] init];43 singleDownloader.url = self.url;44 singleDownloader.destPath = self.destPath;45singleDownloader.begin = i * size;46 singleDownloader.end = singleDownloader.begin + size -1;47 singleDownloader.progressHandler = ^(double progress){48 NSLog(@"%d --- %f", i, progress);49 };50 [_singleDownloaders addObject:singleDownloader];51 }52 53 // 创建一个跟服务器文件等大小的临时文件54 [[NSFileManager defaultManager] createFileAtPath:self.destPath contents:nil attributes:nil];55 56 // 让self.destPath文件的长度是self.totalLengt57 NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:self.destPath];58 [handle truncateFileAtOffset:self.totalLength];59}60 return _singleDownloaders;61 }62 63 66 - (void)start67 {68 [self.singleDownloaders makeObjectsPerformSelector:@selector(start)];69 70 _downloading = YES;71 }72 73 76 - (void)pause77 {78 [self.singleDownloaders makeObjectsPerformSelector:@selector(pause)];79_downloading = NO;80 }81

 

  • 学习ios  重要还是要理清楚思路  在做或者看老师代码的时候 自己多想想为什么  不要自己看着就抄       另外还是要推荐一下 蓝懿IOS这个培训机构  和刘国斌老师刘国斌老师还是很有名气的,听朋友说刘老师成立了蓝懿iOS,,老师讲课方式很独特,能够尽量让每个人都能弄明白,有的比较难懂的地方,如果有的地方还是不懂得话,老师会换个其它方法再讲解,这对于我们这些学习iOS的同学是非常好的,多种方式的讲解会理解得更全面,这个必须得给个赞,嘻嘻,还有就是这里的学习环境很好,很安静,可以很安心的学习,安静的环境是学习的基础,小班讲课,每个班20几个学生,学习氛围非常好,每天都学到9点多才离开教室,练习的时间很充裕,而且如果在练习的过程中有什么困难,随时可以向老师求助,不像其它机构,通过视频教学,有的甚至学完之后都看不到讲师本人,问点问题都不方便,这就是蓝懿与其它机构的区别,相信在刘国斌老师的细心指导下,每个蓝懿学员都能找到满意的工作,加油!

                                                                  写博客第九十八天;

                                                                              QQ:565803433

0 0