UI基础整理-19

//

//  ViewController.m

//  Lesson19_初级数据持久化

//

//  Created by Floating_SH on 15/12/14.

//  Copyright © 2015 SH. All rights reserved.

//


#import "ViewController.h"

#import "Phone.h"

@interface ViewController ()


@end


@implementation ViewController



 - (void)viewDidLoad {

    [superviewDidLoad];

    

// 沙盒文件目录

     /*

    //沙盒主路径

    //每个应用程序运行的时候都会生成一个专属的沙盒路径,应用程序在使用期间的非代码文件都存储在当前的沙盒目录中.

    NSString *homePath = NSHomeDirectory();

    

    NSLog(@"%@",homePath);

    

    

    // Documents :用来存储永久性数据的文件夹,程序运行需要的必要资源(例如数据库)全部存放在这里,iTunes会自动备份此文件夹的内容

    // 第一个参数 :要查询的路径

    // 第二个参数 :要查询的路径所属的用户(iOS下通常为单用户)

    // 第三个参数 :是否显示绝对路径

    // 区别于Mac OS(OS X)的开发,ios开发中通常一个应用程序只有一个文件路径

    // 由于OC同时支持苹果系列的操作系统开发,所以在Mac OS下会生成很多个路径,而在iOS,通常会生成一个路径,所以存储路径的是数组

    // iOS端的路径.只要取出数组中唯一一个元素就可以

    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];//NSDocumentDirectory这里要注意,不要打错

    NSLog(@"%@",documentsPath);

    

    

    // Library : 保存应用程序运行期间生成的内容

    NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)lastObject];

    NSLog(@"%@",libraryPath);

    

    //caches : 主要要用来保存应用程序的缓存文件(iTunes不会自动备份此文件夹)

    NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];

    NSLog(@"%@",cachesPath);

    

    //preferences : 主要用来保存应用程序的偏好设置一般不获取(iTunes会自动备份此文件夹)

    //下方是强行获取preferences的路径

    NSString *preferencesPath = [libraryPath stringByAppendingString:@"/Preferences"];

    NSLog(@"%@",preferencesPath);

    

    // 单例用来存储程序的偏好设置,会写入preferences文件夹,所以通常情况下,我们不直接打开或者操作preferences文件夹,而是通过NSUserDefaults创建的对象来完成偏好设置的内容,并且写到本地

    // 巧用 : NSUserDefaults可以用来传值(单例)

    // NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];

    // [userDefault setBool:YES forKey:@"NightMode"];

    // NSLog(@"%d",[userDefault boolForKey:@"NightMode"]);

    

    

    // tmp : 临时文件夹,应用程序在运行期间产生的临时碎片都会存储在这里,通常在文件下载完成或者是应用程序退出的时候清空此文件夹.iTunes不会备份此文件夹.

    // tips :因为系统会清空,所以下载或者其他临时文件如果想要持久使用要及时转移走

    NSString *tmpPath = NSTemporaryDirectory();

    NSLog(@"%@",tmpPath);

    */

    

     

     

// 简单对象写入文件

     // 字符串写入文件

     /*

     NSString *incantation = @"I love my iOS teacher";

     

     // 设置路径

     NSString *path = NSHomeDirectory();

     path = [path stringByAppendingString:@"/咒语"];

    

     // 写入文件

     // 第一个参数 :路径

     // 第二个参数 :是否进行线性操作 (YES的时候,可以保证发生意外的时候有中转文件来存储数据,直至完成写入,但是损耗较高.NO的时候,是直接写入,写入速度很快,但是没有安全保障)

     // 第三个参数 :编码方式

     // 第四个参数 :错误对象

     [incantation writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];

    

     // 读取文件

     // 第一个参数 :路径

     // 第二个参数 :编码方式 (切记要和写入的时候一致)

     // 第三个参数 :错误对象

     NSString *resultString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

     NSLog(@"%@",resultString);

    */

     // 数组写入文件

     /*

     NSArray *array = @[@"Selina",@"KarTing",@"MLP",@"HellRun",@"Alice",@"TanGa"];

     // 准备文件路径

     NSString *path = NSHomeDirectory();

     path = [path stringByAppendingPathComponent:@"Girls.txt"];

     // 写入文件

     [array writeToFile:path atomically:YES];

     

     // 从文件中获取内容

     NSArray *resultArray = [NSArray arrayWithContentsOfFile:path];

     NSLog(@"%@",resultArray);

    */

     // 字典写入文件

     /*

     NSDictionary *dict = @{@"name":@"sh",@"age":@"20",@"address":@"Beijing"};

     // 准备文件路径

     NSString *path = NSHomeDirectory();

     //path = [path stringByAppendingString:@"/SH"]; //等同于下方

     path = [path stringByAppendingPathComponent:@"SH"];

     // 写入文件

     [dict writeToFile:path atomically:YES];

     

     // 从文件中获取内容

     NSDictionary *resultDict = [NSDictionary dictionaryWithContentsOfFile:path];

     NSLog(@"%@",resultDict);

     */

     // 图片写入文件

     // 获取图片对象

     /*

     UIImage *image = [UIImage imageNamed:@"fallinlove.jpg"];

     // 创建路径

     NSString *path = NSHomeDirectory();

     path = [path stringByAppendingPathComponent:@"love.jpg"];

     // 转化为Data对象

     NSData *data = UIImageJPEGRepresentation(image, 1);//用与图片相对应的方法

     // 写入文件

     [data writeToFile:path atomically:YES];

     

     // 读取内容

     UIImageView *imgView = [[UIImageView alloc]initWithFrame:self.view.bounds];

     imgView.image = [UIImage imageWithContentsOfFile:path];

     [self.view addSubview:imgView];

      */

  

     

     

// 复杂对象写入文件

     /*

     Phone *phone = [Phone new];

     

     phone.color = @"GreatGold";

     phone.brand = @"HuaWei";

     phone.price = @"1999";

     

     // 创建Data对象

     NSMutableData *mutableData = [[NSMutableData alloc]initWithCapacity:3];

     // 创建归档对象

     NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:mutableData];

     // 归档

     [archiver encodeObject:phone forKey:@"p8"];

     // 完成归档

     [archiver finishEncoding];

     //写入文件

     NSString *path = NSHomeDirectory();

     path = [path stringByAppendingPathComponent:@"phone"];

     

     [mutableData writeToFile:path atomically:YES];

     

     

     // 反归档

     // 获取Data对象

     NSData *data = [NSData dataWithContentsOfFile:path];

     // 创建反归档对象

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

     // 反归档

     Phone *resultPhone = [unarchiver decodeObjectForKey:@"p8"];

     // 完成反归档

     [unarchiver finishDecoding];

     NSLog(@"%@ %@ %@",resultPhone.color,resultPhone.brand,resultPhone.price);

     

     

     // 归档不是数据持久化的方式,而是辅助完成将复杂对象转化为NSData对象的方式,真正完成数据持久化的方式仍然是write to file (写入文件)

     

     //-------- 面试题 --------

     // 数据持久化方式

     // 1、属性列表 (plist)

     // 2、偏好设置 (NSUserDefault)

     // 3、写入文件 (write to file)

     // 4、数据库 (sqlite)

     // 5Core Data

     

     //OC里面没有真正意义上的深拷贝,除了归档和反归档

     NSLog(@"%@---%@",phone,resultPhone);

      */

     

     

//文件管理器

     NSURLSessionDownloadTask *downloadTask = [[NSURLSessionsharedSession]downloadTaskWithURL:[NSURLURLWithString:@"http://qzapp.qlogo.cn/qzapp/100410602/1A109B6BFB8F254439C933285FE0FEB2/100"]completionHandler:^(NSURL *_Nullable location,NSURLResponse *_Nullable response,NSError * _Nullable error) {

         

         // 获取Data对象

         NSData *data = [NSDatadataWithContentsOfURL:location];

         // 创建文件管理器

         NSFileManager *fileManager = [NSFileManagerdefaultManager];

         //创建一个文件夹

         NSString *path = NSHomeDirectory();

         path = [path stringByAppendingPathComponent:@"班级照片"];

         // 创建文件夹(运行完就可以注释了,因为创建完就在那了)

         //[fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];

         // 创建文件(同样也是运行一次之后就可以注释了,防止重复创建)

         NSString *filePath = [path stringByAppendingPathComponent:@"Kiss"];

         [fileManager createFileAtPath:filePathcontents:data attributes:nil];

         

         

     }];

     

     [downloadTask resume];

     

     

}







- (void)didReceiveMemoryWarning {

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end




//

//  Phone.h

//  Lesson19_初级数据持久化

//

//  Created by Floating_SH on 15/12/14.

//  Copyright © 2015 SH. All rights reserved.

//


#import <Foundation/Foundation.h>


@interface Phone :NSObject<NSCoding>



@property (strong,nonatomic)NSString *color;

@property (strong,nonatomic)NSString *brand;

@property (strong,nonatomic)NSString *price;



@end




//

//  Phone.m

//  Lesson19_初级数据持久化

//

//  Created by Floating_SH on 15/12/14.

//  Copyright © 2015 SH. All rights reserved.

//


#import "Phone.h"


@implementation Phone


// 复杂对象想要实现数据持久化 (写入文件),必须遵循NSCoding协议,实现以下两个方法

// 编码

// 在这个方法中,我们需要实现每一个需要归档的属性,并标记key

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

    

    [aCoder encodeObject:_colorforKey:@"color"];

    [aCoder encodeObject:_brandforKey:@"brand"];

    [aCoder encodeObject:_priceforKey:@"price"];

}

// 解码

// 在这个方法中,我们需要完成属性的解码操作,根据编码时的key值一一对应获取相应的值

- (instancetype)initWithCoder:(NSCoder *)aDecoder{

    

    if (self = [superinit]) {

        

        _color = [aDecoder decodeObjectForKey:@"color"];

        _brand = [aDecoder decodeObjectForKey:@"brand"];

        _price = [aDecoder decodeObjectForKey:@"price"];

    }

    

    return self;

}

@end











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值